Array manipulation
w3cschool
is a good place to learn basic things, and mozilla documents are more detailed.
Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
1 | // Filtering invalid entries from JSON |
Array.prototype.sort()
The sort() method sorts the elements of an array in place and returns the array.
1 | // Remove duplicates id |
Array.prototype.splice()
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
Remove 0 elements from index 2, and insert “drum”
1 | var myFish = ["angel", "clown", "mandarin", "surgeon"]; |
Remove 1 element from index 3
1 | var myFish = ["angel", "clown", "drum", "mandarin", "surgeon"]; |
Remove 1 element from index 2, and insert “trumpet”
1 | var myFish = ["angel", "clown", "drum", "surgeon"]; |
Remove 2 elements from index 0, and insert “parrot”, “anemone” and “blue”
1 | var myFish = ["angel", "clown", "trumpet", "surgeon"]; |
Remove 2 elements from index 2
1 | var myFish = ["parrot", "anemone", "blue", "trumpet", "surgeon"] |
Remove 1 element from index -2
1 | var myFish = ["angel", "clown", "mandarin", "surgeon"]; |
Array.prototype.slice()
1 | var a = ["zero", "one", "two", "three"]; |
Array.prototype.slice()
1 | var a = ["zero", "one", "two", "three"]; |
Array.prototype.shift()
The shift() method removes the first element from an array and returns that element. This method changes the length of the array.
1 | var a = [1, 2, 3]; |
Array.prototype.unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
1 | var a = [1, 2, 3]; |
Array.prototype.pop()
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
1 | var a = [1, 2, 3]; |
Array.prototype.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.
1 | var a = [2, 9, 9]; |
What is the difference between .map, .every, and .forEach in JavaScript array?
.map() returns a new Array of objects created by taking some action on the original item.
.every() returns a boolean - true if every element in this array satisfies the provided testing function. An important difference with .every() is that the test function may not always be called for every element in the array. Once the testing function returns false for any element, no more array elements are iterated. Therefore, the testing function should usually have no side effects.
.forEach() returns nothing - It iterates the Array performing a given action for each item in the Array.
.find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.