Here are some example of the usage of array methods in JavaScript:
.filter
Creates a new array with all of the elements of this array for which the provided filtering function returns true:
let masiv = [20, 30, 40, 50, 1, 30, 54, 100, 5];
let filterM = masiv.filter(x=>x % 10 == 0);
console.log(filterM);
filterM = filterM.filter(x=>x < 50);
console.log(filterM);
filterM = filterM.map(x=>"the number " + (100 * x));
console.log(filterM);
let masivTwo = ["one", "two", "three", "four", "five"];
let masivThree = masivTwo.filter(x=>x.startsWith("t"));
console.log(masivThree.join("|"));
.join()
The join() method joins all elements of an array (or an array-like object) into a string:
let nums = [10, 20, 30];
console.log(nums.join("|"));
.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array:
nums.push(40);
console.log(nums.join("|"));
.pop()
The pop() method removes the last element from an array and returns that element. This method changes the length of the array:
let tail = nums.pop();
console.log(nums.join("|"));
.shift()
The shift() method removes the first element from an array and returns that element. This method changes the length of the array:
let firstEl = nums.shift();
console.log(firstEl);
.unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the new array:
let otlyavo = nums.unshift(333);
console.log(otlyavo);
console.log(nums);
.slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified:
let sliceEl = nums.slice(2, 3);
console.log(sliceEl);
.splice()
The splice() method changes the contents of an array by removing existing elements and/or adding new elements:
let arrN = [20, 40, 10, 30, 100, 5];
let spliceN = arrN.splice(1, 5);
console.log(spliceN);
console.log(arrN);
let arrNTwo = [20, 40, 10, 30, 100, 5];
let spliceAndReplace = arrNTwo.splice(1, 3, -1, -2, -3);
console.log(spliceAndReplace);
console.log(arrNTwo);
.sort()
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points:
let nomera = [20, 40, 10, 30, 100, 5];
nomera.sort((a, b)=>a - b);//po vazhodyasht red
console.log(nomera);
nomera.sort((a, b)=>b - a);//v nizhodyasht red
console.log(nomera);
.reduce()
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value:
let example = [10, 20, 30].reduce((a, b)=>a + b);
console.log(example);