DEV Community

loading...

Discussion on: JavaScript Array methods: Filter, Map, Reduce, and Sort

Collapse
aminnairi profile image
Amin

Very nice and clear article, thanks Ivana.

Are you using the JavaScript Markdown syntax highlight in all of your code snippets? It looks like they are not rendered as JavaScript snippets but as plain text from my side of view.

Otherwise, one thing I would like to add about this infamous Array.prototype.reduce method is that it can be used as a base to create all of the Array.prototype.* goodies you have talked about and even the every or some methods.

"use strict";

const filterMap = (filterAndUpdate, items) => {
  //             |
  //             |
  //             |
  //             V
  return items.reduce((previousItems, item) => {
    const updated = filterAndUpdate(item);

    if (updated !== false) {
      return [
        ...previousItems,
        updated
      ];
    }

    return previousItems;
  }, []);
};

const users = [
  {id: 1, username: "johndoe", email: "john@doe.com"},
  {id: 2, username: "janedoe", email: "jane@doe.com"},
  {id: 3, username: "linustorvalds", email: "ltorvalds@linux.com"},
];

const ids = filterMap(({email, id}) => email.includes("doe") && id, users);

console.log(ids); // [1, 2]
Enter fullscreen mode Exit fullscreen mode