DEV Community

Zeeshan Ahmd
Zeeshan Ahmd

Posted on

JavaScript array methods

There are many javascript array mehthods but we will discuss only the following:

  • Map
  • Reduce
  • Filter
  • Some
  • Every

Map

This method will executes the callback function on each element of the array.

array.map((item, index, array) => {}, thisValue)
Enter fullscreen mode Exit fullscreen mode

Now lets have a look at the usage of the map method:

const names = ["John", "Jane"];
const greetings = names.map((name, index) => {
    console.log(index);
    return `Hi, ${name}`;
});
console.log(greetings);
Enter fullscreen mode Exit fullscreen mode

Executing above code will output the following:

0, 1
[ "Hi, John", "Hi, Jane" ]
Enter fullscreen mode Exit fullscreen mode

Reduce

This method will reduce the array into one element.

const numbers = [1, 2, 3];
const total = numbers.reduce((total, currentValue) => total + currentValue);
console.log(total);
Enter fullscreen mode Exit fullscreen mode

Executing above code will output the following:

6
Enter fullscreen mode Exit fullscreen mode

Filter

This method will extract all the elements from the array which passed the provided condition inside call back function.

const users = [
  {
    name: 'John',
    isActive: true,
  },
  {
    name: 'Alice',
    isActive: false,
  },
  {
    name: 'Bob',
    isActive: true,
  },
];

const activeUsers = users.filter(user => user.isActive);
console.log(activeUsers);
Enter fullscreen mode Exit fullscreen mode

Executing above code will output the following:

[
  {
    "name": "John",
    "isActive": true
  },
  {
    "name": "Bob",
    "isActive": true
  }
]
Enter fullscreen mode Exit fullscreen mode

Some

This method will return true if one element passed the condition otherwise it will return false.

const users = [
  {
    name: 'John',
    isActive: false,
  },
  {
    name: 'Alice',
    isActive: false,
  },
  {
    name: 'Bob',
    isActive: true,
  },
];

const isOneUserActive = users.some(user => user.isActive === true);
console.log(isOneUserActive);
Enter fullscreen mode Exit fullscreen mode

Executing above code will output the following:

true
Enter fullscreen mode Exit fullscreen mode

Every

This method will return true if all elements passed the condition provided inside callback function otherwise it will return false.

const users = [
  {
    name: 'John',
    isActive: false,
  },
  {
    name: 'Alice',
    isActive: true,
  },
  {
    name: 'Bob',
    isActive: true,
  },
];

const isAllUserActive = users.every(user => user.isActive === true);
console.log(isAllUserActive);
Enter fullscreen mode Exit fullscreen mode

Executing above code will output the following:

false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)