var arr = [
{one: 1},
{one: 2}
]
var result = arr.find( obj => obj.one > 1 );
console.log(result);
// result: {one: 2}
var arr = [
{one: 1},
{one: 2}
]
var result = arr.find( obj => obj.one > 1 );
console.log(result);
// result: {one: 2}
Converting array into object
// The array
var numbers = [1,2,3];
var obj = {...numbers }
console.log(obj)
// result: {0:1, 1:2, 2:3}
Expanding object with new parameter
// The array
var person = {
name: 'Jhon'
}
var obj = {...person, age: 23 }
console.log(obj)
// expected person to be: {name: 'John', age:23 }
Getting sum of an array
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// resunt: 6
The array
// The array
var people = [
{ name: 'john', age: 24, weight: 84 },
{ name: 'tim', age: 34, weight: 76 },
{ name: 'Jack', age: 26, weight: 65 },
];
MAP
// map - use it if I want to do the same operation for each element in the array
// and return the same amount of items in the array.
// array.map(
// current item of the array,
// curent index,
// the entire array
// );
var result = people.map((person, index, persons) => {
return `${person.name}: ${person.age}`;
});
console.log('map', result);
FILTER
// filter - return only items that match certain criteria.
// array.filter(
// current item of the array,
// curent index,
// the entire array
// )
var result = people.filter((person, index, persons) => {
return person.age < 30;
});
console.log('filter', result);
REDUCE
// reduce - return something completely new after iteration through each element
// in the array
// array.reduce(
// current value of the end value,
// current item,
// curent index,
// the entire array
// )
var initialValue = 10;
var combined_weight = people.reduce((weight, person, index, persons) => {
return weight += person.weight;
}, initialValue);
console.log('reduce', combined_weight);
Another example of reduce, that will convert the array of objects, to object of objects, where person.name is going to be the key
var reducer = (accumolator, person) => {
accumolator[person.name] = person;
return accumolator;
}
var initialValue = {};
// reduce takes reducer function as first parameter, and initial value
var result = people.reduce(reducer, initialValue);
console.log('reduce', result);