Create a copy. Modifications on the object will modify the original one too.
const shallowcopyclone = {...myobject};
Create an independent copy. Modifications on the object will NOT modify the original one.
const deepcopyclone = JSON.parse(JSON.stringify(myobject));
const array2 = array1.slice()
simply creates a shallow copy. With parameters like slice(1,3)
you can get parts of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
.forEach(), .map(), .reduce(), .filter(), find(), every(), some()
Here we select odd numbers and add them to our list.
const nums = [79, 48, 12, 4, 48, 33];
const startArray = [3, 7];
const reduceResult = nums.reduce((acc, item, index, source) => {
console.log('new loop turn');
console.log(`acc: ${acc}`);
console.log(`item: ${item}`);
console.log(`index: ${index}`);
console.log(`source: ${source}`);
if(item % 2) acc.push(item);
return acc;
}, startArray);
console.log(startArray);
console.log(nums);
console.log(reduceResult);
! pretty often the best way to find is to use some or every
find if element exists in array. Returns first array item fulfilling conditions, undefined
if not item found.
const findNums = [79, 48, 12, 4, 48, 33];
const findIt1 = findNums.find(item => item === 12);
console.log('findIt 1 - ', findIt1);
const findIt2 = findNums.find(item => item === 8);
console.log('findIt 2 - ', findIt2);
const findObjectArray = [
{ name: 'jack', fullName: 'flap jack', data: [1, 2, 3, 4, 5, 6]},
{ name: 'john', fullName: 'john does', data: [1, 2, 3, 4, 5, 6]},
{ name: 'jack', fullName: 'bad jack', data: [1, 2, 3, 4, 5, 6]},
{ name: 'mary', fullName: 'mary blood', data: [1, 2, 3, 4, 5, 6]},
]
const findIt3 = findObjectArray.find(item => item.name === 'jack');
console.log('findIt3 - ', findIt3);
check if all the list elements contain hours and seconds (find if there is an invalid item)
const timeList = [
'11:23`,
'13:23`,
'08:59`,
'99:99`,
null,
undefined,
];
const regexMatch = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
const isEveryValid = timeList.every((time) =>
time !== null
&& time !== undefined
&& time.length === 5
&& time.match(regexMatch));
const nums = [79, 48, 12, 4];
function compare(a, b) {
if (a > b) return 1;
if (b > a) return -1;
return 0;
}
nums.sort(compare);
// => 4, 12, 48, 79
It is the same, just logs the algorithm:
const nums = [79, 48, 12, 4, 48, 33];
function compare(a, b) {
if (a > b) {
console.log(`a=${a} is greater than b=${b}`)
return 1;
}
if (b > a) {
console.log(`a=${a} is fewer than b=${b}`)
return -1;
}
console.log(`a=${a} equals b=${b}`)
return 0;
}
nums.sort(compare);
console.log(nums);
ES6
const nums = [79, 48, 12, 4, 48, 33];
nums.sort((a,b) => {
if (a > b) return 1;
if (b > a) return -1;
return 0;
});
console.log(nums);
Typical example: date sorting with moment.js's .diff() function:
const sortedArray = array.sort((a, b) => a.diff(b))
.forEach(), .map(), .reduce(), .filter(), find(), every(), some()
🦀 Each receives a callback function as a parameter.
🐬 You can always replace explicit callback functions with fat arrow functions. If it is handy, you can replace the function body with the return value to make the code tinier. So these are the same callback functions:
function (ageParam) { return ( { name: 'jack', age: ageParam }) }
(ageParam) => { return ( { name: 'jack', age: ageParam }) }
ageParam => ({ name: 'jack', age: ageParam }) ---> I had to put parentheses, so it is an object, not a code block
- Reduce is for general array processing. It can result any type of value: object, array, string, number. This is the only one we use with two parameters. First parameters is the Callback Function, second is the Starting Value. The callback function can use four parameters: accumulator, item, item index and the original starting value.
- The every() and some() return true or false and the callback function should also return true or false . These are to check if some or every array items fulfils a condition.
- The find() excepts a callback function to return true or false and returns the first true item. If there can be multiple fitting items, use filter() instead! .map() is to create an array from an array, with the same size.
const people = [
{ _id: "person_1", name: "Steve Jobs", age: 56, isAlive: false, likeHim: false},
{ _id: "person_2", name: "Elon Musk", age: 49, isAlive: true, likeHim: false},
{ _id: "person_3", name: "Bob Ross", age: 52, isAlive: false, likeHim: true},
{ _id: "person_4", name: "Mark Zuckerberg", age: 36, isAlive: true, likeHim: false}
];
const hellos = ['hello', 'hi', 'hey', 'yo', 'hiya', 'howdy'];
const fiveYearsLater = people.map(person => {
return {
...person,
age: person.age + 5
}
});
const names = people.map(person => person.name);
const thePersonILike = people.find(person => person.likeHim);
const onePersonIDontLike = people.find(person => !person.likeHim); // we only get the first!
const peopleIDontLike = people.filter(person => !person.likeHim); // we get all of them
const peopleAlive = people.filter(person => person.isAlive);
const isAnyoneAlive = people.some(person => { return person.isAlive } );
const areAllPeopleAlive = people.every(person => person.isAlive);
// returns a number
const averageAge = ( people.reduce((acc, person) => acc + person.age, 0) ) / people.length;
// returns an object, found in the array
const oldestPerson = people.reduce((oldest, person) => {
return (oldest.age > person.age) ? oldest : person;
});
// returns a string, assembled by using the array
const sayHelloForEveryBody = people.reduce((acc, person, personIndex, original) => {
const isLastPerson = personIndex === original.length - 1;
return `${acc}${hellos[Math.floor(Math.random() * hellos.length)]} ${person.name}${isLastPerson ? '!' : ', '}`;
}, '');
// return an object which has different properties
const apocalypseEstimation = people.reduce(
(acc, person) => {
const { age, isAlive } = person;
if (isAlive) {
acc.alive++;
acc.totalAge += age;
} else {
acc.dead++;
}
return acc;
},
{ alive: 0, dead: 0, totalAge: 0 }
);
// start value is a non-empty array and extract information into it
const peopleOfMyBand = people.reduce((acc, person) => {
if (person.likeHim || person.isAlive) {
acc.push({ fullName: person.name, hobby: 'music' });
}
return acc; // I have to return the accumulator!
},[
{ fullName: 'Jack Black', hobby: 'guitar' },
{ fullName: 'Phil Collins', hobby: 'drums' },
]);