Array iteration : 8 methods in JS

//forEach()
//it's pretty straightforward, it just does something for each item in the array
[1,2,3].forEach(function(item,index){
    console.log(item, index); // 1,0---2,1---3,2
});

//map()
//it takes the item that's from the array, 
//it does something to it and then puts a new thing back in that same place in the array
const numbers = [1,2,3];
const doubled = numbers.map(function(item,index){
    return item*2;
});
console.log(doubled); // [2,4,6]
console.log(numbers);  // [1,2,3];

//filter()
//it's gonna take an array and it's gonna check each item in the array
//it gets again some kind of condition to see it it's true or false
//if it's true, it's going to put the item back in the array
const ints = [1,2,3];
const evens = ints.filter(function(item){
    return item%2 === 0;
});
console.log(evens); // [2]
console.log(ints); // [1,2,3]

//reduce
//we're going to do something and then pass the result to the next iteration along with the next item in the array
//the number at the end is what the initial result is going to be
//if you don't put a number at the end like that
//the initial result will be the first item in the array
const sum = [1,2,3].reduce(function(result,item){
    return result+item;
},0);
console.log(sum); // 6

//some()
//just check if any item in the array
//does any item in the entire array meet this condition
//so if any item in the entire array meets the condition
//it will return true
const hasNegativeNumbers = [1,2,3,-4].some(function(item){
    return item < 0;
});
console.log(hasNegativeNumbers); // true

//every()
//it's kind of similar to some()
//but now every number has to meet the condition

const hasPositiveNumbers = [1,2,3].every(function(item){
    return item > 0
}); 
console.log(hasPositiveNumbers); // true

//find()
//it goes through every item in the array
//and check it against the condition, if that's true, it returns that item
const objects = [{id:'a'},{id:'b'},{id:'c'}];
const found = objects.find(function(item){
    return item.id === 'b';
});
console.log(found);  // {id:'b'}

//findIndex()
const objects2 = [{id:'a'},{id:'b'},{id:'c'}];
const foundIndex = objects.findIndex(function(item){
    return item.id === 'b';
});
console.log(foundIndex);  // 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值