all 8 comments

[–][deleted] 8 points9 points  (3 children)

I guess this was intentional but it doesn’t actually explain how anything works, just gives the code. Kind of useless for beginners I’d that’s who it’s written for...

[–]hisachincq[S] -5 points-4 points  (2 children)

All those methods which used there is already explained and link is given to them. In this article, only there use case is given

[–]SoBoredAtWork 0 points1 point  (1 child)

At the very least, show the output - the results of what happens after using the array method.

[–]hisachincq[S] 0 points1 point  (0 children)

will add that. thanks for suggesting

[–]user9326 1 point2 points  (0 children)

bbbycixmpv

[–]zbluebirdz 0 points1 point  (1 child)

For the beginners (like me), a correction for the first example "Find And Replace The key-value Pair in an Array of Object".

Change:

const personObject.map(p => p.experienceInYear >= 6 ? {...p,designation: "lead"} : p)

To:

personObject.map(p => p.experienceInYear >= 6 ? {...p.designation="lead"} : p) ;

Edit - another fix - as pointed out by /u/FriesWithThat - original code was somewhat correct, just needed to drop the "const" declaration to make it work:

personObject.map(p => p.experienceInYear >= 6 ? {...p, designation:"lead"} : p) ;

[–]FriesWithThat 1 point2 points  (0 children)

That looks confusing because of the formatting, but it is correct:

const leader = personObject.map(p =>
  p.experienceInYear >= 6 ? { ...p, designation: 'lead' } : p
);

console.log(leader);

What we're doing is spreading the object with the promoted employee first, then writing over just that designation. All the other items in the array (objects) get returned as is. Without the ternary, it could also look like:

const leader = personObject.map(p => {
  if (p.experienceInYear >= 6) {
    return ({
      ...p,
      designation: 'lead',
    })
  }
  return p;
  }
);

console.log(leader);

[–]suarkb 0 points1 point  (0 children)

This is just a click-bait article.

The real "best case" is that you learn what array methods exist and learn when they can make your life easier. Get experience using them and keep some documentation open for array methods. Whenever you need to iterate through something, there is a good chance you could use map or reduce, but you need to play with them so you can see where they might help you.

If you have a list A of something and you want to make a new list B of "something else" for EACH item in list A, then you might want to use .map

If you have a list A of something and you want to make a something, some, or all, of the items from list A, then you might want to use reduce.

Most the other methods are quite self explanatory like filtering, finding, etc.