//Advanced Arrays
const array = [1, 2, 10, 16];
const newArray = array.forEach((num) => {
num * 2;
} )
console.log(newArray);
we should use push to make it new.
//Advanced Arrays
const array = [1, 2, 10, 16];
const double = []
const newArray = array.forEach((num) => {
double.push(num * 2);
} )
console.log(double);
Map have a return element.
//Advanced Arrays
const array = [1, 2, 10, 16];
const double = []
const newArray = array.forEach((num) => {
double.push(num * 2);
} )
console.log('forEach',double);
// map, filter, reduce
const mapArray = array.map((num)=> {
return num * 2;
});
console.log('map', mapArray);
^'map' is shorter and simpler than 'forEach'.
If you have a single parameter with an arrow function, you can actually avoid the brackets.
const mapArray = array.map((num)=> {
return num * 2;
});
const mapArray = array.map(num=> {
return num * 2;
});
And again because we're returning a single line here we can do like this.
const mapArray = array.map(num=> num * 2);
.
//Advanced Arrays
const array = [1, 2, 10, 16];
const double = []
const newArray = array.forEach(num => {
double.push(num * 2);
} )
console.log('forEach',double);
// map, filter, reduce
const mapArray = array.map(num=> num * 2);
console.log('map', mapArray);
//Advanced Arrays
const array = [1, 2, 10, 16];
const double = []
const newArray = array.forEach(num => {
double.push(num * 2);
} )
console.log('forEach',double);
// map, filter, reduce
const mapArray = array.map(num=> num * 2);
console.log('map', mapArray);
//filter
const filterArray =array.filter( num => {
return num > 5
})
console.log('filter', filterArray);
//Advanced Arrays
const array = [1, 2, 10, 16];
const double = []
const newArray = array.forEach(num => {
double.push(num * 2);
} )
console.log('forEach',double);
// map, filter, reduce
const mapArray = array.map(num=> num * 2);
console.log('map', mapArray);
//filter
const filterArray =array.filter( num => num === 5);
console.log('filter', filterArray);
acc is accumulator
//reduce
const reduceArray = array.reduce((accumulator, num)=>{
return accumulator + num;
},0)
Here accumulator's default value is 0.
//Advanced Arrays
const array = [1, 2, 10, 16];
const double = []
const newArray = array.forEach(num => {
double.push(num * 2);
} )
console.log('forEach',double);
// map, filter, reduce
const mapArray = array.map(num=> num * 2);
console.log('map', mapArray);
//filter
const filterArray =array.filter( num => {
return num > 5
})
console.log('filter', filterArray);
//reduce
const reduceArray = array.reduce((accumulator, num)=>{
return accumulator + num;
},0)
console.log('reduce', reduceArray);
^we get 29 ( 1+2+10+16 = 29 )
If you change the default value of accumulator to 5,
//reduce
const reduceArray = array.reduce((accumulator, num)=>{
return accumulator + num;
},5)