You must know JavaScript array methods
Himanshu Gupta
Posted on February 27, 2023
. Pop()
The pop() method removes the last element from an array.
let arr = [“Apple”, “Amazon”, “Flipkart”, “Walmart”];arr.pop();
Output:
["Apple", "Amazon", "Flipkart"]
. Shift ()
The shift() method removes the first array element and shifts all other elements to a lower index.
let arr = [“Apple”, “Amazon”, “Flipkart”];arr.shift();
Output:
["Amazon", "Flipkart"]
. Unshift ()
The unshift() method adds a new element to the beginning of an array and unshifts older elements.
let arr = [“Amazon”, “Flipkart”];arr.unshift("Apple");
Output:
["Apple", "Amazon", "Flipkart"]
. sort()
The sort() method works only for string type and sort array items in ascending order.
const stringArray = ['f', 'z', 'd', 'x', 'a'];
const numberArray = [5, 9, 1, 19, 56];
Output:
stringArray.sort() // ["a", "d", "f", "x", "z"]
numberArray.sort() // [1, 19, 5, 56, 9]
. map( )
This is one of the useful array methods in my knowledge. What it does is, this method iterates all through the array and creates a new array of values from the original array. If it’s confusing to understand, imagine that there is an array called “cars”. It has a key, value pair of brand and model. Using the code below, you can understand what I am saying.
const cars = [{ brand: "Toyota", model: "axio" },{ brand: "Nissan", model: "GTR R35" },];const carBrands = cars.map((car) => {return car.brand;});console.log(carBrands);// expected output: Array ["Toyota", "Nissan"]
I think now you have an idea how a map() method works. Let’s move into the next method.
. Reverse ()
The reverse() method reverses the order of the elements in an array.
let arr = ["Apple", "Amazon", "Google", "Walmart"];arr.reverse();
Output:
["Walmart", "Google", "Amazon", "Apple"]
. filter( )
This method looks similar to the map() method. But with this function, you can give a condition/criteria and it will return a new array that falls under the given condition/criteria. Take a look at the below code snippet and you can understand the behavior of the filter() method.
const names = ["James", "Freddie", "Johnson", "Nelson", "Jenny", "George"];const result = names.filter((name) => {
return name.length > 6;
});console.log(result);// expected output: Array ["Freddie", "Johnson"]
What happens in the above code snippet is it filters out the “names” array under the condition of “name.length > 6”. So, inside the method, it checks each value and returns the values that satisfy the given condition. Pretty straightforward, right? Let’s move on.
. copyWithin()
This method copies array elements to another position in the array, overwriting the existing values.
This method will never add more items to the array.
const numbers = [1,2,3,4];
const numbersCopy = numbers.copyWithin(2,0);
Output:
console.log(numbersCopy); // [1,2,1,2];
. forEach( )
I’m sure that you know the for loop. If I say this is the simplest type of for loop, I think you’ll agree with me after getting to know about this method. So, take a look at the given code snippet.
const array = ["a", "b", "c"];array.forEach((element) => console.log(element));
Output:
// expected output: "a"
// expected output: "b"
// expected output: "c"
When using the forEach() method, it executes a provided function once for each array element.
. find( )
Using this method you can find a single object in an array. It also takes a single function with a given name as the parameter. All we do is we have a true or false statement and it returns the item for the first one where it’s true. Take a look at the below code snippet
const cars = [{ brand: "Toyota", model: "axio" },{ brand: "Nissan", model: "GTR R35" },];
const carBrands = cars.find((car) => {return car.brand === "Nissan";});
console.log(carBrands);// expected output: Object { brand: "Nissan", model: "GTR R35" }
I think now you have a clear idea about the find() method. But there’s one thing to remember. If there’s a key, value pair with same key or value, this method doesn’t return all the objects. It only returns the object that is true.
. every( )
Using this method, you can check the array with some condition. What does that mean is you can give a condition and every() method checks to make sure every single item falls under that. Then as the result, it returns the true or false .
const books = [{ name: "book 01", price: 500 },{ name: "book 02", price: 100 },{ name: "book 03", price: 400 },{ name: "book 04", price: 700 },{ name: "book 05", price: 200 },{ name: "book 06", price: 600 },];const hasCheaperBooks = books.every((book) => {return book.price <= 400;});console.log(hasCheaperBooks);//expected output: false
As the name of the method, this checks every single item that satisfies the given condition. Since there are books greater than 400, this method will return false as the output. The next array method is very similar to this method. So… let’s take a look at what it is all about.
. Slice ()
you can use slice() to remove elements without leaving holes in the array.
The first parameter defines the position where new elements should be added.
The second parameter defines how many elements should be removed.
let arr = ["Apple", "Amazon", "Google", "Walmart"];arr.splice(1,1);
Output:
["Apple", "Google", "Walmart"]
. some( )
In the every() method it checks the every single item that satisfies the given condition and it returned true or false . When it comes to some() method, as the name of the method it checks if some of the items in the array satisfy the given condition and return true or false . Take a look at the same example we used in every() function and see how it changes when it comes to some() method.
const books = [{ name: "book 01", price: 500 },{ name: "book 02", price: 100 },{ name: "book 03", price: 400 },{ name: "book 04", price: 700" },{ name: "book 05", price: 200 },{ name: "book 06", price: 600 },];const hasCheaperBooks = books.some((book) => {return book.price <= 400;});console.log(hasCheaperBooks);//expected output: true
The output of the example is true because it does have books less than or equal to 400. In simple terms, it just checks the array to see if anything in the array returns true for the given condition. If it does, the entire thing returns true .
. reduce( )
This method is a little bit different than all of the other methods since it’s actually doing some operation on the array and returning a combination of all those different operations. You may find this method is a little bit confusing to understand🤨, but I’ll explain in the simplest way I can.
The reduce() method takes a function and it has two parameters. 1st one is the previousValue . 2nd one is currentValue . Finally, end of the method there is initialValue . Take a look at the below code snippet and you will understand this confusing explanation.
const books = [{ name: "book 01", price: 500 },{ name: "book 02", price: 100 },{ name: "book 03", price: 400 },{ name: "book 04", price: 700 },{ name: "book 05", price: 200 },{ name: "book 06", price: 600 },];const total = books.reduce((currentTotal, book) => {return book.price + currentTotal;}, 0);console.log(total);//expected output: 2500
You can see the initial value of the currentTotal is 0. In the 1st iteration, 500 will be added to the 0. Then the currentTotal will be 500. Like that it will run until the end of the array. Then it’ll return the final output as 2500.
. Splice ()
The splice() method can be used to add new items(one or more) to an array.
The first parameter defines the position where new elements should be added.
The second parameter defines how many elements should be removed.
The rest of the parameters define the new elements to be added.
This method returns an array with the deleted items.
let arr = [“Apple”, “Amazon”, “Flipkart”, “Walmart”];arr.splice(2, 1, "Google");
Output:
["Apple", "Amazon", "Google", "Walmart"]
. includes( )
The includes() method determines whether a given array includes a certain value among its entries, returning true or false as appropriate. It’s not similar to all the methods that I mentioned earlier in this article. This doesn’t take a function, it takes a single argument. Referring to code snippet, you can understand what happens when you use the includes() method.
const array = [1, 2, 3];console.log(array.includes(3));
// expected output: trueconst pets = ['cat', 'dog', 'parrot'];console.log(pets.includes('dog'));
// expected output: trueconsole.log(pets.includes('pig'));
// expected output: false
I think the code snippet describes the behavior of the includes() method because it’s easier than previously describes methods.
. findIndex()
This method returns the index of the element in an array that passes a condition. It executes the function once for each element present in the array.
If the condition fails, it simply returns -1.
const numbers = [1,2,3,4];
const indexFound = numbers.findIndex(element => element === 3);
numbers.findIndex(element => element === 5);
Output:
console.log(indexFound); //2const indexNotFound
console.log(indexNotFound); // -1
. Join ()
The join() method returns an array as a string. It does not change the original array. We can specify any separator. Otherwise, the default is a comma(,).
let arr = [“Apple”, “Amazon”, “Flipkart”, “Walmart”];let str = arr.join("-");
Output:
Apple-Amazon-Flipkart-Walmart
. Concat ()
The concat() method creates a new array by merging existing arrays.
let arr = [“Apple”, “Amazon”, “Flipkart”];arr.concat("Walmart");
Output:
["Apple", "Amazon", "Flipkart", "Walmart"]
Thank you for keep reading.
Posted on February 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.