DEV Community

Cover image for Everything you need to know about Javascript Arrays
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

Everything you need to know about Javascript Arrays

With arrays, there are usually a set number of specific things you want to achieve. Below is a list of pretty much any action you would want to perform on an array, and how to do it in Javascript. If you have any more, let me know in the comments below!

1. Find Index of an Element by Value

Use indexOf:

let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ];

// Returns 1
console.log(arr1.indexOf('banana'));

// Returns -1 since not found
console.log(arr1.indexOf('beetroot')); 
Enter fullscreen mode Exit fullscreen mode

2. Delete at Index

Use splice(). More detail instructions on deleting items from a Javascript array can be found here too!.

let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ];

// Returns [ 'banana', 'ravioli', 'carrot' ], since potato has index 0.
arr1.splice(0, 1);
console.log(arr1);
Enter fullscreen mode Exit fullscreen mode

3. Delete at Index by Value

Use splice() and indexOf:

let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ];
let itemIndex = arr1.indexOf('ravioli');

// Returns [ 'potato', 'banana', 'carrot' ], since ravioli has an index of 2
arr1.splice(itemIndex, 1);
console.log(arr1);
Enter fullscreen mode Exit fullscreen mode

4. Get the last element of an array

Use arr.length() - 1:

let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ];

// Returns carrot
console.log(arr1[arr1.length - 1]);
Enter fullscreen mode Exit fullscreen mode

5. Insert at Index

Use splice(). You can also read about inserting at an index in detail here.

let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ];

// Inserts broccoli at position 2, after deleting 0 items
arr1.splice(2, 0, 'broccoli');

// Returns [ 'potato', 'banana', 'ravioli', 'brccoli', 'carrot' ]
console.log(arr1);
Enter fullscreen mode Exit fullscreen mode

6. Remove the last element of the array

Use pop():

let arr1 = [ 1, 2, 3, 4, 5, 6 ];

// Returns 6
console.log(arr1.pop()); 

// Returns [ 1, 2, 3, 4, 5 ] - last element is removed
console.log(arr1);
Enter fullscreen mode Exit fullscreen mode

7. Change all values of an array in the same way

Use map():

let arr1 = [ 1, 2, 3, 4, 5, 6 ];

let newArr = arr1.map(function(arrElement) {
    return arrElement + 3;
})

// ES6 version for modern browsers and NodeJS
let anotherVersion = arr1.map( el => el + 3);

// Returns [ 4, 5, 6, 7, 8, 9 ] for both
console.log(newArr);
console.log(anotherVersion);
Enter fullscreen mode Exit fullscreen mode

8. Turn a string, map, or set into an array

Use Array.from():

let newSet = new Set([ 'orange', 'apple', 'potato', 'spinach' ]);
let newMap = new Map([ 'orange', 'apple', 'potato', 'spinach' ]);
let newString = 'apple';

console.log(Array.from(newSet)); // Returns [ 'orange', 'apple', 'potato', 'spinach' ]
console.log(Array.from(newMap)); // Returns [ 'orange', 'apple', 'potato', 'spinach' ]
console.log(Array.from(newString)); // Returns [ 'a', 'p', 'p', 'l', 'e' ]
Enter fullscreen mode Exit fullscreen mode

9. Check if it is an array

Use Array.isArray():

let arr1 = [ 'orange', 'apple', 'potato', 'spinach' ];
let obj1 = { myKey: "myValue" }

console.log(Array.isArray(arr1)); // Returns true
console.log(Array.isArray(obj1)); // Returns false
Enter fullscreen mode Exit fullscreen mode

10. Check every element in an Array

Use forEach:

let arr1 = [ 'orange', 'apple', 'potato', 'spinach' ];

arr1.forEach(function(item) {
    console.log(item); // Returns each array item individually
});
Enter fullscreen mode Exit fullscreen mode

11. Merge two arrays

Use ... or concat:

let arr1 = [ 'orange', 'apple' ];
let arr2 = [ 'potato', 'spinach' ];

// For legacy browsers (ES5);
// Returns [ 'orange', 'apple', 'potato', 'spinach' ]; 
let someArray = arr1.concat(object);

// For modern Javascript (ES6/NodeJS)
// Returns [ 'orange', 'apple', 'potato', 'spinach' ]; 
let someOtherArray = [ ...arr1, ...arr2 ];
Enter fullscreen mode Exit fullscreen mode

12. Turn object names into array

Use Object.keys:

let object = { 
    name1: "value",
    name2: "value",
    name3: "value"
};

// Returns [ 'name1', 'name2', 'name3' ]; 
let array = Object.keys(object);
Enter fullscreen mode Exit fullscreen mode

13. Turn object values into arrays

Use Object.values:

let object = { 
    name1: "value",
    name2: "value",
    name3: "value"
};

// Returns [ 'value', 'value', 'value' ]; 
let array = Object.values(object);
Enter fullscreen mode Exit fullscreen mode

14. Reverse an Array

Use reverse():

let arr1 = [ 'potato', 'banana', 'carrot' ];

arr1.reverse();

// Returns [ 'carrot', 'banana', 'potato' ]
console.log(arr1);
Enter fullscreen mode Exit fullscreen mode

15. Sum all Elements in an Array

Use reduce():

let arr1 = [ 1, 2, 3, 4, 5 ];

// For legacy browsers
let getTotal = arr1.reduce(function (accumulator, currentNumber) {
    return accumulator + currentNumber
});

// ES6 for modern browsers and NodeJS
let theTotal = arr1.reduce((accumulator, currentNumber) => accumulator + currentNumber);

// Returns 15
console.log(getTotal);
Enter fullscreen mode Exit fullscreen mode

16. Add an Elements to the end of an array

Use push():

let arr1 = [ 'banana', 'potato' ];

arr1.push('broccoli');

// Returns [ 'banana', 'potato', 'broccoli' ]
console.log(arr1);
Enter fullscreen mode Exit fullscreen mode

17. Check if every element of an array passes a test

Use every()

let arr1 = [ 1, 2, 3, 4, 5, 6, 7 ];

// Will return true and console log 'great'
if(arr1.every(value => value < 10)) {
    console.log('great!')
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (1)

Collapse
 
receter profile image
Andreas Riedmüller

In Javascript it is also quite important to know about the concept of sparse arrays. Because an array can have empty slots (which differs from slots "filled" with undefined) that not even get iterated, this is the case eg. if you call the Array constructor.

Create a new Array with n entries:

const array1 = new Array(10) // Sparse array with 10 empty slots, can not be iterated yet
const array2 = [...new Array(10)]; // 10 entries with undefined values
const array3 = [...new Array(10).keys()]; // 10 entries filled with numbers [0, ... , 9]
Enter fullscreen mode Exit fullscreen mode