DEV Community

Cover image for Learn all the Array methods in JavaScript
Posandu  ๐Ÿš€
Posandu ๐Ÿš€

Posted on • Originally published at tronic247.com

Learn all the Array methods in JavaScript

In this article, we'll learn about the array methods in JavaScript with some examples. Before we start, let's look at some methods of the Array class.

Array()

Accepts 1 integer argument and returns an array with those elements.

Array(10) // Array(10) [ <10 empty slots> ]
Array() // Array []
Enter fullscreen mode Exit fullscreen mode

.from()

We use this method to create an array. It accepts two arguments, the first one accepts an array or some iterable object.

Array.from("never") // Array(5) [ "n", "e", "v", "e", "r" ]
Enter fullscreen mode Exit fullscreen mode

The second argument is for the mapping function (scroll below to learn more about map), it is optional.

Array.from("never", (el, i) => el + i) 
// Array(5) [ "n0", "e1", "v2", "e3", "r4" ]
Enter fullscreen mode Exit fullscreen mode

.isArray()

This method accepts 1 argument and returns if it's an array.

Array.isArray("") // false
Array.isArray() // false
Array.isArray(42) // false
Array.isArray([]) // true
Enter fullscreen mode Exit fullscreen mode

Now, we'll go to the main part of this article.

.at()

Returns the element of the array of the given position. You can use negative numbers instead of doing array[array.length-1].

["a","b","c","d","e"].at(0) // a
["a","b","c","d","e"].at(-1) // e
["a","b","c","d","e"].at(42) // undefined
Enter fullscreen mode Exit fullscreen mode

.concat()

Merges all the arguments to one array.

["hello"].concat("world", "bye", "world", [5]) 
// Array(5) [ "hello", "world", "bye", "world", 5 ]
Enter fullscreen mode Exit fullscreen mode

.copyWithin()

Copies the array within a range. Accepts 3 arguments.

["1","2","3","4","5","6"].copyWithin(0) 
// Array(6) [ "1", "2", "3", "4", "5", "6" ]

["1","2","3","4","5","6"].copyWithin(3, 0) 
// Array(6) [ "1", "2", "3", "1", "2", "3" ]

["1","2","3","4","5","6"].copyWithin(3, 0, 4) 
// Array(6) [ "1", "2", "3", "1", "2", "3" ]
Enter fullscreen mode Exit fullscreen mode

.every()

Accepts a test function and returns a boolean if all the elements of the array pass the test.

["gonna", "give", "you"].every((element) => element.startsWith("g")) // false

["apple", "android", "aluminium"].every((element) => element.startsWith("a")) // true
Enter fullscreen mode Exit fullscreen mode

.fill()

Fills the array with a given value. Accepts 3 arguments. 1st argument is the value we need to fill. The 2nd argument is the starting index. The last argument is the ending index. The last two parameters are optional.

Array(10).fill(1) // Array(10) [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]

Array(10).fill(1, 5)
// Array(10) [ <5 empty slots>, 1, 1, 1, 1, 1 ]

Array(10).fill(1, 2, 4) 
// Array(10) [ <2 empty slots>, 1, 1, <6 empty slots> ]
Enter fullscreen mode Exit fullscreen mode

.filter()

Accepts a test function to loop each array element and remove that element if failed the test.

["eating", "sleeping", "coding", "playing"].filter(element => element != "sleeping")
// Array(3) [ "eating", "coding", "playing" ]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(element => element % 2)
// Array(5) [ 1, 3, 5, 7, 9 ]
Enter fullscreen mode Exit fullscreen mode

.find()

Again, this accepts a test function and returns the element that the test function passed.

const people = ["John", "Anna", "Peter", "Rick", "Elon"]
const search = name => people.find(element => element.startsWith(name))

search("Jo") // "John"
search("Rick") // "Rick"
search("Ben") // undefined
Enter fullscreen mode Exit fullscreen mode

.findIndex()

Does the same thing as .find(). Instead of returning the value, returns the position of the element in the array.

const people = ["John", "Anna", "Peter", "Rick", "Elon"]
const search = name => people.findIndex(element => element.startsWith(name))

search("Jo") // 0
search("Rick") // 3
search("Ben") // -1
Enter fullscreen mode Exit fullscreen mode

.flat()

Flats the array to a given depth. The depth will be 1 if no value.

[1, [2, [3, [4]]], 5].flat() // Array(4) [ 1, 2, (2) [โ€ฆ], 5 ]

[1, [2, [3, [4]]], 5].flat(2) // Array(5) [ 1, 2, 3, (1) [โ€ฆ], 5 ]

[1, [2, [3, [4]]], 5].flat(3) // Array(5) [ 1, 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

.forEach()

Accepts an argument that will call for each element of the array

["one","two","three","four"].forEach(alert) // Alerts 4 times
Enter fullscreen mode Exit fullscreen mode

.includes()

Returns if the array contain the given value. Also, this is case-sensitive.

["ant","bat","cat","rat","man"].includes("man") // true
["ant","bat","cat","rat","man"].includes("Man") // false
["ant","bat","cat","rat","man"].includes("dog") // false
Enter fullscreen mode Exit fullscreen mode

.indexOf()

Returns the least index of an element of the array (if found) after searching the value. Returns -1 if not found. The 2nd argument specifies the position to start the search.

["ant","bat","cat","rat","man"].indexOf("man") // 4

["ant","bat","cat","rat","man"].includes("Man") // -1

["ant", "bat", "cat", "rat", "man"].includes("ant", 2) // -1
Enter fullscreen mode Exit fullscreen mode

.join()

Joins all the array elements into a string with a separator (if given).

["up", "never", "gonna", "let", "you", "down"].join` `
Enter fullscreen mode Exit fullscreen mode

.lastIndexOf()

Does the same thing as .indexOf. Instead of giving the least index, this gives you the largest index.

["a", "aaa", "aaa", "aa", "a", "aaa"].lastIndexOf("aaa") // 5
["a", "aaa", "aaa", "aa", "a", "aaa"].lastIndexOf("b") // -1
Enter fullscreen mode Exit fullscreen mode

.map()

Loops for each element of the array and executes the given function and change the value to the output of the function.

["a","b","c","d","e","f","g"].map(e=>e.toUpperCase()) 
// Array(7) [ "A", "B", "C", "D", "E", "F", "G" ]
Enter fullscreen mode Exit fullscreen mode

.pop()

Removes the last element of the array and returns it. (You may know stack operations)

let arr = ["a","b","c","d","e","f","g"]
console.log(arr.pop()) // g
console.log(arr) // ["a","b","c","d","e","f"]
Enter fullscreen mode Exit fullscreen mode

.shift()

Removes the first element and return that element.

let arr = ["a","b","c","d","e","f","g"]
console.log(arr.shift()) // a
console.log(arr) // ["b","c","d","e","f","g"]
Enter fullscreen mode Exit fullscreen mode

.push()

Push the given value to the array. Then, return the new length of the array.

let h = ["hello"]
console.log(h.push("world")) // 2
console.log(h) // Array [ "hello", "world" ]
Enter fullscreen mode Exit fullscreen mode

.unshift()

Does the same as .push but adds the elements to the first.

let h = ["hello"]
console.log(h.unshift("world")) // 2
console.log(h) // Array [ "world", "hello"]
Enter fullscreen mode Exit fullscreen mode

.reduce()

Accepts a reducer function as the first argument and executes it. If you can't understand that, see below. The second arguments show the initial value, and it's optional.

To calculate the sum of an array, we can do this.

let tot = 0
const array = [1, 2, 3, 4, 5]
array.forEach(e => (tot += e))
console.log(tot) // 15
Enter fullscreen mode Exit fullscreen mode

There is no problem of doing that, but we can use .reduce() to that.

const tot = [1, 2, 3, 4, 5].reduce((previous, current) => previous + current, 0)

console.log(tot) // 15
Enter fullscreen mode Exit fullscreen mode

.reduceRight()

Same as .reduce() but executes from the last to start of the array. If we do a quick test, we can see this.

[1, 2, 3, 4, 5].reduceRight((previous, current) => {
  console.log("current: ", current)
  return previous + current
})
Enter fullscreen mode Exit fullscreen mode

Outputs

image

.reverse()

Reverse the array!

[1, 2, 3, 4, 5].reverse() // Array(5) [ 5, 4, 3, 2, 1 ]
Enter fullscreen mode Exit fullscreen mode

.slice()

Imagine cutting an array like cutting a vegetable. This method does the same. It accepts 2 arguments. The start index and the end.

["head","neck","body","feet"].slice() // (same array)

// WARNING : weird creatures ahead

["head","neck","body","feet"].slice(1) 
// Array(3) [ "neck", "body", "feet" ]

["head", "neck", "body", "feet"].slice(1, 3)
// Array [ "neck", "body" ]
Enter fullscreen mode Exit fullscreen mode

.some()

Accepts a function that tests and returns if one or more elements of the array passes that.

const ages = [42, 69, 1, 25, 34, 14]
ages.some(age => age > 60) // true
Enter fullscreen mode Exit fullscreen mode

.sort()

Sorts an array and returns the sorted array. You can also use your own sorting function.

[1, 2, 4, 8, 4, 2, 1, 6, 8, 4, 2, 7, 56, 2, 9, 5, 52, 1].sort()

// Array(18) [ 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, โ€ฆ ]
Enter fullscreen mode Exit fullscreen mode

Using your own sorting function

let people = [{
    name: "Andrew",
    age: 19
  }, {
    name: "Posandu",
    age: 14
  }, {
    name: "Luke",
    age: 17
  },
  {
    name: "Ben",
    age: 23
  }
]

console.log(people.sort((a, b) => a.age > b.age))

/*
0: Object { name: "Posandu", age: 14 }
1: Object { name: "Luke", age: 17 }
2: Object { name: "Andrew", age: 19 }
3: Object { name: "Ben", age: 23 }
*/

Enter fullscreen mode Exit fullscreen mode

And that's all you need to learn about the array methods in JavaScript! I publish more like this on my blog https://www.tronic247.com/

Discussion (2)

Collapse
andrewbaisden profile image
Andrew Baisden

Looking through this list reminds me why as developers we sometimes need to refer to the documentation there is so much to remember ๐Ÿ˜… Great guide by the way.

Collapse
posandu profile image
Posandu ๐Ÿš€ Author

thanks!