English

11 most popular methods dealing with array

3/31/2024
20

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.    

JavaScript
const array = [{ id: 1, name: 'John' }];
array.push({ id: 2, name: 'Jane' });

2. pop(): Removes the last element from an array and returns it.  

JavaScript
const lastElement = array.pop();

3. shift(): Removes the first element from an array and returns it.  

JavaScript
const firstElement = array.shift();

4. unshift(): Adds one or more elements to the beginning of an array.  

JavaScript
array.unshift({ id: 3, name: 'Alice' });

5. Splice(): Adds or removes elements from an array at a specified index.  

JavaScript
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.  

JavaScript
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.  

JavaScript
const mappedArray = array.map(obj => obj.name.toUpperCase());

8. find(): Returns the first element in the array that satisfies the provided testing function.  

Plaintext
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.  

Plaintext
const foundIndex = array.findIndex(obj => obj.id === 2);

10. forEach(): Executes a provided function once for each array element.  

JavaScript
array.forEach(obj => console.log(obj.name));

11.sort(): Sorts the elements of an array in place and returns the sorted array.  

JavaScript
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.