Loop traversal: map(), filter(), for loop, forEach(), entries(), Set(arr), array deduplication, every(), some()

Native JS  forEach() and map() traversal

Common points:

     1. Are looping through each item in the array.

     2. ForEach() and map() each time the anonymous function is executed, 3 parameters are supported: the current item in the array, the index of the current item, and the original array input.

     3. This in anonymous functions refers to Window.

     4. Only the array can be traversed.


One: map() does not change the original array

There is a return value, which can be returned.

The map can change the value of the current loop and return a new array after the changed value (map needs to return) without changing the original array. It is generally used to modify the value of an array.

Take the field value of the object array and re-assign the key value pair into a new array


var ary = [12,23,24,42,1];
var res = ary.map(function (item,index,input) {
    return item*10;
})
console.log(res);//-->[120,230,240,420,10];
console.log(ary);//-->[12,23,24,42,1];


//根据属性值查找,并更改该属性值
oldArry: [
     { id: 0,  flag:false},
     { id: -2, flag:true},
],

mounted(){
    let newArry = this.oldArry.map(item => {
            if (item.flag === true) {
                item.flag = false;
            }
            return item;
        });
        
    }
}
//打印结果
//console.info(newArry)//newArry:[{id:0,flag:false}, { id: -2, flag:fasle},]

//console.info(this.oldArry)//[{id:0,flag:false},{ id: -2, flag:true},]

 


Two: foEach() changes the original array

 No return value


 // 循环遍历
        traversal(){
            var arr = [1,2,3,4,5,6,7]
            var res = arr.forEach(function (item,index,input) {
                input[index] = item*10;
            })
            console.log(res);//-->undefined;
            console.log(arr);//-->会对原来的数组产生改变[10, 20, 30, 40, 50, 60, 70]
        },

 


Three: for loop


 


Four: filter()        does not change the original array

The filter function can be regarded as a filter function, returning an array of eligible elements


(1) filter() filter non-compliant items


let arr = [1,2,3,4,5,6,7]
let newArr = arr.filter(item => item>=3)  
console.log(newArr)//[3, 4, 5, 6, 7]

arr = [1,2,3,4,5];
console.info(arr.filter(item => ![1,2,3].includes(item)));
----> [4, 5]

(2) js removes empty values ​​and false values ​​in the array

var arr=[undefined,undefined,1,'','false',false,true,null,'null'];
let newArr = arr.filter(item => item)
console.log(newArr)//newArr = [1, "false", true, "null"]

(3) filter() array deduplication

let arr = [1, 2, 2, 3, 4, 5, 5, 6,6];
let newArr = arr.filter((x, index,self)=>self.indexOf(x)===index) 
console.log(newArr)//newArr = [1, 2, 3, 4, 5, 6]


//对象数组去重 根据id去重
newArr = [
    {id:1, name:'Amy'},
    {id:2, name:'Tom'},
    {id:3, name:'Sunny'},
    {id:1, name:'Amy'}
];
newArr = arr.filter((x, index)=>{
     let ruleIds = [];
     arr.forEach((item) => {
          ruleIds.push(item.id);
      });
   return ruleIds.indexOf(x.id) === index;
});
console.info(newArr);//结果如下图

Recommended methods for array deduplication:

let arr = [1, 2, 2, 3, 4, 5, 5, 6,6];
let newArr =Array.from(new Set(arr)) 
console.log(newArr)//newArr = [1, 2, 3, 4, 5, 6]

(4)filter() Filter array objects----->Single condition filter:


let arr = [
    {a:'苹果',b:'面包',c:'吃'},
    {a:'香蕉',b:'面包',c:'不吃'},
    {a:'香蕉',b:'苹果',c:'吃'},
    {a:'苹果',b:'香蕉',c:'不吃'},]
let newArr = arr.filter(item => {
   return item.a === '苹果'
})
console.log(arr)
console.log(newArr)

第二种写法
     let arr = [
          {a:'苹果',b:'面包',c:'吃'},
          {a:'香蕉',b:'面包',c:'不吃'},
          {a:'香蕉',b:'苹果',c:'吃'},
          {a:'苹果',b:'香蕉',c:'不吃'},
     ]
    let newArr = arr.filter(item => item.a === '苹果')
        console.log(arr)
        console.log(newArr)
}

Consistent results

------->Multiple conditions filter

let a = '苹果'; //筛选参数a
            let b = '面包'; //筛选参数b
            let c = ''     //筛选参数c
            let arr = [
                    {a:'苹果',b:'面包',c:'吃'},
                    {a:'香蕉',b:'面包',c:'不吃'},
                    {a:'香蕉',b:'苹果',c:'吃'},
                    {a:'苹果',b:'香蕉',c:'不吃'},
                ]; 
let newArr = arr.filter( item => (a?item.a === a : true) && (b?item.b === b : true) && (c?item.c === c : true))
console.log(newArr);

写法二:
let a = '苹果'; //筛选参数a
let b = '面包'; //筛选参数b
let c = ''     //筛选参数c
let arr = [
    {a:'苹果',b:'面包',c:'吃'},
    {a:'香蕉',b:'面包',c:'不吃'},
    {a:'香蕉',b:'苹果',c:'吃'},
    {a:'苹果',b:'香蕉',c:'不吃'},
]; 
let newArr = arr.filter(item => {
  return (a?item.a === a : true) && (b?item.b === b : true) && (c?item.c === c : true)
})
console.log(newArr)

Consistent results: 


五、Array.prototype.entries()

Object.entries(), the method returns an array of key-value pairs of the enumerable properties of the given object itself

对象:Object.entries()

dataFruits:{"a":"Banana", "b":"Orange", "c":"Apple", "d":"Mango"}

console.log(Object.entries(this.dataFruits));//结果图1

//key-value
for (const [key, value] of Object.entries(this.dataFruits)) {
          console.log(key,value);// 结果 图3
}

                      

数组 array.entries()

fruits: ["Banana", "Orange", "Apple", "Mango"],

for(let [index,value] of this.fruits.entries()){
            console.info(index,value);//结果 图2
}

Note: When using entries() for objects and numbers, the writing is different

If the object is written as shown in the picture when using entries(), it will report an error

 


 

Six, every(), some() array iteration method.

some has been looking for a value that meets the conditions, and once found, it will not continue to iterate.
Every starts from the iteration, once one does not meet the conditions, it will not continue to iterate.

every() is to run a given function for each item in the array. If the function returns true for each item, it returns true.
1. If one element in the array is not satisfied, the entire expression returns false, and the remaining elements will not be tested again.
2. If all elements meet the conditions, return true.

some() is to run a given function on each item in the array, and if the function returns true for any item, it returns true.
1. If an element meets the condition, the expression returns true, and the remaining elements will not be tested.
2. If there is no element that meets the condition, false is returned.

var arr = [1, 2, 3, 4, 5]
console.log(arr.some((item, index, array) => {
  return item > 3
}))     // true
console.log(arr.every((item, index, array) => {
  return item > 3
}))      // false

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/Sunny_lxm/article/details/98625716