A method of efficiently reduce weight to achieve the object array

We know the definition of access to information can reduce method

reduce () method takes a function as an accumulator, each value in the array (left to right) started to shrink, as a final calculated value

Seen from the definition of this method seems to be calculated, but in fact in addition, as an advanced method, it has a lot Sao operating
on reducesome conventional methods using reference here

reduce grammar

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

accumulator :( accumulator, the accumulated callback return value; the cumulative value which is returned when a callback is invoked, or the initialValue)
currentValue :( current element processed)
index :( index element currently being processed)
Array reduce the call :( source array)
the initialValue :( as the first parameter when the first call to the callback function values. If no initial value, the first element in the array will be used. reduce call on an empty array will be no initial value error)

Well, the end of the methods described below to show an operation, requirements: duplicate objects in the object array is removed .
For general array is a common treatment either use a temporary array and then loops through either indexOf judge, senior point using the new data type Set ES6 directly to the heavy, but for an array of objects I have personally tested, hard to deal with, but also cumbersome, the following code uses reduce the direct method:

	var resources = [
            { name: "张三", age: "18" },
            { name: "张三", age: "19" },
            { name: "张三", age: "20" },
            { name: "李四", age: "19" },
            { name: "王五", age: "20" },
            { name: "赵六", age: "21" }
        ]
     var temp = {};
     resources = resources.reduce((prev, curv) => {
         // 如果临时对象中有这个名字,什么都不做
         if (temp[curv.name]) {
         }
         // 如果临时对象没有就把这个名字加进去,同时把当前的这个对象加入到prev中
         else {
             temp[curv.name] = true;
             prev.push(curv);
         }
         return prev
     }, []);
     console.log("结果", resources);

Here Insert Picture Description
It should be noted here only initialValuehave to put an empty array [], or can not push, once you understand the process reduce, then it is well understood for a long time to realize how heavy, just to name according to the judge, if there are other needs, you can still add a judgment to achieve their goals.

Guess you like

Origin blog.csdn.net/moqiuqin/article/details/94552397