11 most popular methods dealing with array
The most important methods for dealing with arrays containing objects in JavaScript
1. push(): Adds one or more elements to the end of an array.
const array = [{ id: 1, name: 'John' }];
array.push({ id: 2, name: 'Jane' });
2. pop(): Removes the last element from an array and returns it.
const lastElement = array.pop();3. shift(): Removes the first element from an array and returns it.
const firstElement = array.shift();4. unshift(): Adds one or more elements to the beginning of an array.
array.unshift({ id: 3, name: 'Alice' });5. Splice(): Adds or removes elements from an array at a specified index.
array.splice(1, 1); // Remove one element at index 1
array.splice(1, 0, { id: 4, name: 'Bob' }); // Add an element at index 1
6. filter(): Creates a new array with all elements that pass the test implemented by the provided function.
const filteredArray = array.filter(obj => obj.id === 1);7. map(): Creates a new array populated with the results of calling a provided function on every element in the calling array.
const mappedArray = array.map(obj => obj.name.toUpperCase());
8. find(): Returns the first element in the array that satisfies the provided testing function.
const foundElement = array.find(obj => obj.name === 'Alice');
9. findIndex(): Returns the index of the first element in the array that satisfies the provided testing function.
const foundIndex = array.findIndex(obj => obj.id === 2);
10. forEach(): Executes a provided function once for each array element.
array.forEach(obj => console.log(obj.name));
11.sort(): Sorts the elements of an array in place and returns the sorted array.
array.sort((a, b) => a.id - b.id);
These methods provide powerful tools for manipulating arrays containing objects in JavaScript. Depending on your specific use case, you may find some of them more useful than others.
