There are some common Javascript Array methods we use in JavaScript. In this article, I tried to highlight some of the common array methods I mostly used in JavaScript even in React projects.
I have provided the 16 most used JavaScript methods. I have also included code examples for easier understanding.
Let’s Go!!!
length()
Returns the number of elements in an array.
console.log(colors.length);
Output:
toString()
Converts the elements of an array into a string and returns the result.
console.log(colors.toString());
Output:
indexOf()
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
console.log(colors.indexOf(‘green‘));
Output:
pop()
Removes the last element from an array and returns that element.
const removedColor = colors.pop();
console.log(removedColor);
Output:
push()
Adds one or more elements to the end of an array and returns the new length of the array.
const newLength = colors.push(‘blue‘);
console.log(colors);
Output:
concat()
Returns a new array that combines the original array’s elements with other arrays or values.
const moreColors = colors.concat([‘blue‘, ‘yellow‘]);
console.log(moreColors);
Output:
slice()
Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).
const slicedColors = colors.slice(1, 3);
console.log(slicedColors);
Output:
splice()
Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
colors.splice(2, 1, ‘orange‘); // Removes 1 element starting from index 2 and adds ‘orange’
console.log(colors);
Output:
filter()
Creates a new array with all elements that pass the test implemented by the provided function.
const filteredColors = colors.filter(color => color.length > 4);
console.log(filteredColors);
Output:
find()
Returns the value of the first element in the array that satisfies the provided testing function, or is undefined if no such element is found.
const foundColor = colors.find(color => color === ‘green‘);
console.log(foundColor);
Output:
forEach()
Executes a provided function once for each array element.
colors.forEach(color => console.log(color.toUpperCase()));
Output:
GREEN
BLUE
includes()
Determines whether an array includes a certain element, returning true or false as appropriate.
console.log(colors.includes(‘yellow‘));
Output:
map()
Creates a new array populated with the results of calling a provided function on every element in the calling array.
const capitalizedColors = colors.map(color => color.toUpperCase());
console.log(capitalizedColors);
Output:
reduce()
Executes a reducer function (that you provide) on each array element, resulting in a single output value.
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum);
Output:
If you found this helpful, please consider giving it a like. It means a lot to me. Thanks for Reading 🩵⭐