JavaScript's developers looking to better their coding should be familiar with the most popular ES5 and ES6+ array techniques.
In this article, we'll discuss various built-in JavaScript array functions that can make your life easier, provide you the ability to perform some magical operations on any Array, and prevent you from having to write duplicate code. You'll also learn when and how to use different strategies. Without further ado, let's start.
Array.forEach
The Array.forEach method has the following syntax:
- 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:
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']
*/
Depending on the situation, you might find it useful to use the index and array options.
The forEach method does not return any value, which is something you need to be aware of.
Check out the code below:
const returnedValue = names.forEach(function (name) {
return month;
});
console.log('returnedValue: ', returnedValue); // undefined
Remember that using forEach only works when processing or logging requires looping across the array. It doesn't return anything even if you explicitly return a value from the callback function (this means that the returned value comes as undefined in the above example).
When to use the forEach method
Observe that after the iteration, it returns "undefined". If you intend to push to an array outside the forEach function, for instance, you should consider utilizing the forEach method rather than using it if you intend to return a value.
Array.map
In contrast to the forEach function, the map array technique creates a brand-new array whenever it is applied to an array. The array is iterated over while each value or element is treated to a callback function, and then the new array is returned.
Of all the array techniques, the Array map method is the most beneficial and popular.
The initial array on which the map method is invoked remains unchanged.
Check out the code below:
const transformedArray = names.map((name) => {
return name.toUpperCase();
});
console.log(transformedArray); // ["SHIVAM", "RAVI", "VARSHA", "RAJ"]
When to use the map method
The map method allows an array to be changed into a fresh array, produced, and then returned. If a new value won't be returned from the callback or if the new array it produces won't be used, the map method shouldn't be used.
If you wish to extract only particular data from the array, such as in the following example:
{ 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]
Array.find
The locate find method returns the value of the first array component whose value matches the callback function's expression. If the callback does not contain a matcher for the expression, the search method will return undefined.
Let's say we have a user list that looks like this:
{ name: 'Shivam', age: 24 },
{ name: 'Ravi', age: 26 },
{ name: 'Varsha', age: 23 },
{ name: 'Raj', age: 18 }
];
and we wish to acquire the user record for 'Varsha'. In this case, we can make use of the find technique, as seen below:
return user.name.indexOf('Varsha') > -1;
});
console.log(user); // { name: "Varsha", age: 23 }
When to use the find method
Use the find method when you only need one element in an array to match your callback's expression. If you want to include all the results in your expression, think about utilizing the filter array approach.
Array.filter
A new array containing all the elements that meet the given test criterion is returned by the filter method.
{ 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 }]
The result of the callback will be evaluated as a Boolean. If the callback function returns true for a particular value in the array, that value will be added to the new array; alternatively, if it returns false, the callback will go on to the next item in the array.
The sequence of the parameters is important; the value of the item comes first, then the index, and finally the full array.
When to use the filter method
Use the filter method to display just the objects or values in an array that match your callback's expression.
Array.every
After deciding if each element of the array fulfils the test conditions, the every method generates a boolean value of true or false.
let allPositive = numbers.every((number) => {
return number > 0;
});
numbers = [1, 3, 24, 5];
allPositive = numbers.every((number) => {
return number > 0;
});
console.log(allPositive); // true
Without developing a lot of code, it enables us to quickly determine whether all the pieces meet a set of requirements.
When to use the every method
When determining whether each element in the array satisfies the test requirements.
Array.some
The some method executes the supplied function's test condition and, if at least one member of the array passes, returns a boolean value of true or false.
Let us look at below code:
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
When to use the some method
Let's say we want to determine whether an array of numbers contains at least one positive element. To accomplish it, we can employ a few techniques.
Array.reduce
Each element of the array is subjected to a reducer function (that you specify) as part of the reduce method, which results in a single output value.
Keep in mind that the reduction method's result is always a single value. It could be a number, a string, an object, an array, or anything else. It depends on what you want the reduction method's output to produce, but there is only ever one value produced.
Let's say you wish to determine the array's total number of elements. The reduction approach is appropriate here.
const sum = numbers.reduce((accumulator, number) => {
return accumulator + number;
}, 0);
console.log(sum); // 15
The callback function that gets accumulator, number, index, and array as the values is accepted by the reduce method. Only the accumulator and the number are used in the code above.
The accumulator will hold the initialValue to be used for the array. The initialValue determines the return type of the data that the reduce method returns.
- 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
If you need to add a set of numbers that are part of an array. Similar to how you would have to add up all the product amounts in an online shopping basket and show the user the total.
Conclusion
This article examined a number of built-in JavaScript array methods that can be used to manipulate the array. The first parameter in the methods we've covered is a callback function that may be used to perform an operation on the array.
I sincerely hope that the majority of you find the approach covered here to be helpful. Thank you for reading, and please feel free to leave any comments or questions in the comments section below.
0 Comments