How to use built-in JavaScript Array Functions?

JavaScript provides nice built-in array functions that we can use to work with arrays.

Unlike with the JavaScript object functions are called with Object dot keys, object dot values or Object dot assign, the functions that we use with arrays aren’t called on a global array object.

They’re called from the arrays themselves.

push()

The push() method adds a new element to an array (at the end).

let numbers = [6, 9, 11, 5, 7];
numbers.push(4);
console.log(numbers); //[6, 9, 11, 5, 7, 4]

pop()

The pop() method removes the last element from an array.

We can assign the element that was removed to a new variable if we want.

let numbers = [6, 9, 11, 5, 7, 4];
let last = numbers.pop();
console.log(last); // 4

How to insert/remove an element in the middle/beginning of an array?

We can insert/remove an element in the middle of an array using the array method splice().

splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.

splice(start, deleteCount, item1, item2, itemN)

Parameters:

  • start – The index at which to start changing the array;
  • deleteCount Optional – Is an integer indicating the number of elements in the array to remove from start;
  • item1, item2, … Optional – The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array;

Return value

An array containing the deleted elements.

If only one element is removed, an array of one element is returned.

If no elements are removed, an empty array is returned.

Remove an element from an array

let numbers = [6, 9, 11, 5, 7, 4];
console.log(numbers.splice(2,1)); // 11 The element that we removed

console.log(numbers); // [6, 9, 5, 7, 4]

Add an element to an array

let numbers = [6, 9, 11, 5, 7];
numbers.splice(2, 0, 3);

console.log(numbers); // [6, 9, 3, 11, 5, 7]

Remove the first element and add 2 elements at the beginning of the array

let numbers = [6, 9, 11, 5, 7];
numbers.splice(0, 1, 3, 4);

console.log(numbers); // [3, 4, 9, 11, 5, 7]

indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

let numbers = [6, 9, 11, 5, 7];
console.log(numbers.indexOf(11)); // 2
console.log(numbers.indexOf(15)); // -1

find()

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

If no values satisfy the testing function, undefined is returned.

find() executes the callbackFn function once for each index of the array until the callbackFn returns a truthy value.
If so, find() immediately returns the value of that element.

let numbers = [6, 9, 11, 5, 7];

result = numbers.find(function (x){
    return x > 5;
});
console.log(result); // 6

Notice that the original array is intact.

sort()

The sort() method sorts an array alphabetically.

Be careful when trying to sort numerically arrays!

let num = [1,3,10,4,5];
console.log(num.sort()); //[ 1, 10, 3, 4, 5 ]

Why?

Because JavaScript sorts alphabetically.

This means that “10” is lower than “4” because “1” is lower than “4”.

How to sort a numeric array in JavaScript?

The syntax of the sort method in JavaScript:

array.sort([compareFunction]);

When compare eFunction is not provided:

When compare Function is not provided, the default mode of sorting is followed wherein the elements of the array are converted into strings and then compared according to the UTF 16 code unit values, and the elements are sorted in ascending order by default.

When compare Function is provided:

When compareFunction is provided, then the function takes over the sorting process and all the non-undefined elements get sorted based on the return value of compareFunction according to the following logic.

How to sort a numeric array in ascending order?

sort(function(a,b){return a-b});

How to Sort a numeric array in descending order?

sort(function(a,b){return b-a});

reverse()

The reverse() method reverses the order of the elements in an array.

The reverse() will change the original array.

console.log(['h', 'e', 'l', 'l', 'o'].reverse());
[ 'o', 'l', 'l', 'e', 'h' ]

filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

let numbers = [6, 9, 11, 5, 7];

result = numbers.filter(function (x){
    return x > 5;
});
console.log(result); // [6, 9, 11, 7]

Notice that the original array is intact.

map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

let numbers = [6, 9, 11, 5, 7];

let result = numbers.map(function(x){
    return x * 2;
});

console.log(result);// [12, 18, 22, 10, 14]

Notice that the original array is intact.

The best practice is to use JavaScript’s built-in array methods to work with arrays, instead of using for-loops.

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

Leave a Comment

WebPedia.net