DEV Community

Cover image for Javascript Advance Array Methods You Should Know
Shivam Singh
Shivam Singh

Posted on

Javascript Advance Array Methods You Should Know

The most popular ES5 and ES6+ array methods should be familiar to JavaScript developers who seek to improve their coding.

In this post, we'll talk about certain built-in JavaScript array functions that will simplify your life, giving you the power to execute some magical operations on any Array, and help you avoid writing duplicate code. Additionally, you'll discover how and when to employ various techniques. Let's get started without further ado.

Array.forEach

The Array.forEach method has the following syntax:

Array.forEach((element, index, array) => { /* … */ })
Enter fullscreen mode Exit fullscreen mode
  • element: The current element being processed in the array.
  • index: The index of the current element being processed in the array.
  • array: The array forEach() was called upon.

Take a look at the below code:

const names = ['Shivam', 'Ravi', 'Varsha', 'Raj'];

names.forEach((name, index, array) => {
  console.log(name, index, array);
});

/* output

Shivam 0 ['Shivam', 'Ravi', 'Varsha', 'Raj']
Ravi 1 ['Shivam', 'Ravi', 'Varsha', 'Raj']
Varsha 2 ['Shivam', 'Ravi', 'Varsha', 'Raj']
Varsha 3 ['Shivam', 'Ravi', 'Varsha', 'Raj']

*/
Enter fullscreen mode Exit fullscreen mode

You could find it helpful to use the index and array options, depending on the necessity.

The thing you need to keep in mind is that the forEach method does not return any value.

Take a look at the below code:

const names = ['Shivam', 'Ravi', 'Varsha', 'Raj'];
const returnedValue = names.forEach(function (name) {
  return month;
});

console.log('returnedValue: ', returnedValue); // undefined
Enter fullscreen mode Exit fullscreen mode

Keep in mind that forEach is only employed when looping through the array to carry out processing or logging. Even if you explicitly return a value from the callback function, it doesn't return anything (this means that the returned value comes as undefined in the above example).

When to use the forEach method
Observe that it returns "undefined" following the iteration. The forEach method should not be used if you plan to return a value, but you should think about using it if you plan to, example, push to an array outside of the forEach function.

Array.map

When the map array method is used on an array, it generates a completely new array, unlike the forEach function. Each value or element in the array is subjected to a callback function while the array is iterated over, and then the new array is returned.
The Array map method is the most useful and widely used array method among all other methods.

The map method does not change or mutate the original array it is called on.
Take a look at the below code:

const names = ['shivam', 'ravi', 'varsha', 'raj'];

const transformedArray = names.map((name) => {
  return name.toUpperCase();
});

console.log(transformedArray); // ["SHIVAM", "RAVI", "VARSHA", "RAJ"]

Enter fullscreen mode Exit fullscreen mode

When to use the map method
An array can be transformed into a new array, created, and then returned using the map method. The map method shouldn't be used if a new value won't be returned from the callback or if the new array it creates won't be used.

The array map method is also useful, if you want to extract only specific data from the array like this:

const users = [
  { name: 'Shivam', age: 24  },
  { name: 'Ravi', age: 26 },
  { name: 'Varsha', age: 23 },
  { name: 'Raj', age: 18 }
];

const names = users.map(function (user) {
  return user.name;
});

console.log(names); // ["Shivam", "Ravi", "Varsha", Raj]
Enter fullscreen mode Exit fullscreen mode

Array.find

The value of the first array member whose value matches the callback function's expression is returned by the locate find method. The search method will return undefined if the callback has no matcher to the expression.

Suppose, we have a list of users like this:

const users = [
  { name: 'Shivam', age: 24  },
  { name: 'Ravi', age: 26 },
  { name: 'Varsha', age: 23 },
  { name: 'Raj', age: 18 }
];
Enter fullscreen mode Exit fullscreen mode

and we want to obtain the user's record for 'Varsha'. We can utilise the find method in this situation, as demonstrated below:

const user = users.find((user) => {
  return user.name.indexOf('Varsha') > -1;
});

console.log(user); // { name: "Varsha", age: 23 }
Enter fullscreen mode Exit fullscreen mode

When to use the find method
When you only want a single value in an array that matches your expression in the callback, use the find method. Consider using the filter array method if you want all of the results in your expression.

Array.filter

The filter method returns a new array with all the elements that satisfy the provided test condition.

const users = [
  { name: 'Shivam', age: 24  },
  { name: 'Ravi', age: 26 },
  { name: 'Varsha', age: 23 },
  { name: 'Raj', age: 18 }
];

const user = users.find((user) => {
  return user.age >= 24;
});

console.log(user);
 // [{ name: "Shivam", age: 24 },{ name: "Ravi", age: 26 }]
Enter fullscreen mode Exit fullscreen mode

The callback's outcome will be assessed as a Boolean. A specific value in the array will be added to the new array if the callback function returns true for that value; otherwise, if it returns false, the callback will go on to the next item in the array.

Note: the order of the parameters matter, the first is the value of the item followed by the index and then the entire array.

When to use the filter method
When you only list of object or value in an array that matches your expression in the callback, use the filter method.

Array.every

The every method produces a boolean value of true or false after determining whether each element in the array satisfies the test conditions.

let numbers = [0, -3, 5, -8];

let allPositive = numbers.every((number) => {
  return number > 0;
});
console.log(allPositive); // false 

numbers = [1, 3, 24, 5];

allPositive = numbers.every((number) => {
  return number > 0;
});
console.log(allPositive); // true
Enter fullscreen mode Exit fullscreen mode

It allows us to quickly check if all the elements match certain criteria without writing a lot of code.

When to use the every method
When you want to check that each element in the array satisfies the test conditions or not.

Array.some

The specified function's test condition is tested by the some method, which returns a boolean value of true or false depending on whether at least one member in the array passes.

Let us look at below code:

let numbers = [0, -3, 5, -8];

let containsPositive = numbers.some((number) => {
  return number > 0;
});
console.log(containsPositive); // true 

numbers = [-1, -3, -24, -5];

containsPositive = numbers.some((number) => {
  return number > 0;
});
console.log(containsPositive); // false
Enter fullscreen mode Exit fullscreen mode

When to use the some method
Suppose we have an array of numbers and we want to check if the array contains at least one positive element. We can use the some method to achieve it.

Array.reduce

The reduce method produces a single output value by applying a reducer function (that you supply) to each element of the array.

Note that the output of the reduce method is always a single value. It can be an object, a number, a string, an array, and so on. It depends on what you want the output of reduce method to generate but it's always a single value.

Suppose that you want to find the sum of all the numbers in the array. You can use the reduce method for that.

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, number) => {
  return accumulator + number; 
}, 0);

console.log(sum); // 15
Enter fullscreen mode Exit fullscreen mode

The reduce method accepts a callback function that receives accumulator, number, index and array as the values. In the above code, we’re using only accumulator and number.

The initialValue to be used for the array will be in the accumulator. The return type of the data returned by the reducemethod is determined by the initialValue.

  • accumulator : The value resulting from the previous call to callbackFn. On first call, initialValue if specified, otherwise the value of array[0].
  • currentValue : The value of the current element. On first call, the value of array[0] if an initialValue was specified, otherwise the value of array[1].
  • currentIndex : The index position of currentValue in the array. On first call, 0 if initialValue was specified, otherwise 1.
  • array : The array reduce() was called upon.

When to use the reduce method
when you want to add a group of numbers that are in an array. Like in the instance of an online shopping cart, where you must sum up all product quantities and provide the user the final total.

Conclusion

Several built-in JavaScript array methods that can be used to operate on the array were covered in this article. In the methods we've discussed, the first parameter is a callback function that can be used to do some sort of operation on the array.

Thanks for reading!

Top comments (0)