const array1 = ["This", "is", "an", "array"];
const object = {
first: "1",
second: "2"
};
const array2 = [
{ first: "1", second: "2" },
{ first: "1st", second: "2nd"}
];
Function | Does |
---|---|
.push() |
Appends to the end |
.unshift() |
Adds to the beginning |
.pop() |
Removes last item |
.shift() |
Removes first item |
.indexOf() |
Returns index (number) of item in array |
.splice(pos, num) |
Removes number of items [num] from starting point [pos] |
.slice() |
Make a copy |
.some(function(item)) |
Returns true or false if any items match given statement |
.every(function(item)) |
Returns true or false if all items match given statement |
.forEach(function(item,index)) |
Loops over each item and performs the function |
.find(function(item)) |
Returns the first item that matches the given statement |
.findIndex(function(item)) |
Returns the index of first item that matches the given statement |
const newArray1 = oldArray1.filter(function(item){
if (item === true) {
return true; // keep it
}
});
const newArray2 = oldArray2.filter(item => item === true);
Do you need to return a new array (with the same length as the original) having done some manipulation to each?
const newArray1 = oldArray1.map(function(item){
return item + 1;
});
const newArray2 = oldArray2.map(item => item + 1);
newVar1 = 0;
const newArray1 = oldArray1.reduce(function(newVar1, item){
newVar1 = newVar1 + item;
return newVar1;
});
const newArray2 = oldArray2.reduce((newVar2, item) => {
return newVar2 + item;
}, 0);
const newArray1 = oldArray1.sort(function(firstItem, nextItem){
if (firstItem > nextItem) {
return -1;
} else {
return 1;
}
});
const newArray2 = oldArray2.map((firstItem, nextItem) => {
return firstItem > nextItem ? -1 : 1;
});
Note: Not only does this create a new variable with reference to the array but it also sorts the original array.
Object.entries(someObj).forEach(([key, value]) => {
doSomething(key, value);
});
Updating an new array that was created from referencing an old array will also update the old array, instead, make a copy.
const copiedArray1 = oldArray.slice();
const copiedArray2 = Array.from(oldArray); // ES6
But this is only 1 level deep. In order to ensure that all levels are copied without reference to the old:
const copiedObject1 = JSON.parse(JSON.stringify(oldObject); // sort of hacky, think about whether you really need to manipulate the object
const copiedObject2 = Object.assign({}, oldObject); // ES6