遍历数组并获得给定名称的最低2个条目

时间:2016-07-13 07:19:59

标签: arrays node.js lodash

我有一个带有“name”键和“points”的数组。特定名称可以有多个条目。使用基于点的名称,点和新键类型形成新数组的理想方法是什么。 例: 输入:

password_2

输出:

CMD xvfb-run ./node_modules/gulp/bin/gulp.js test

1 个答案:

答案 0 :(得分:0)

我认为这是一个很好的解决方案:

const input = [{"name":"A", "points": 9},
                {"name":"A", "points": 5},
                {"name":"A", "points": 4},
                {"name":"A", "points": 1},
                {"name":"A", "points": 3},
                {"name":"A", "points": 6},
                {"name":"B", "points": 5},
                {"name":"B", "points": 1},
                {"name":"B", "points": 2},
                {"name":"B", "points": 3}];

//this function will be passed to Array's "reduce" function, and will return the item with the lowest points
const reduceLowest = (lowest, current) => current.points < lowest.points ? current : lowest;

//this function receives an item and returns a new item with an additional "type" property
const addType = (item, typeToAdd) => { return { name : item.name, points : item.points, type : typeToAdd } };

//this function receives an array and returns another array with its two lowests items (typeA and typeB)
const returnTypeATypeB = (arr) => {

    var lowestTypeA = arr       
        .reduce(reduceLowest) //gets the lowest item
        ;

    var lowestTypeB = arr
        .filter((item) => item != lowestTypeA) //removes the item that already is the lowest from the array     
        .reduce(reduceLowest) //gets the lowest item
        ;

    //return an array containing the typeA and typeB items
    return [ addType(lowestTypeA, "typeA"), addType(lowestTypeB, "typeB")];

};          

const output = 
    returnTypeATypeB(
        input.filter((item) => item.name === "A")
    ) //gets typeA and typeB from the items which contains the name "A"
    .concat( //concat the previous list with..
        returnTypeATypeB(
            input.filter((item) => item.name === "B") 
        ) //typeA and typeB from the items which contains the name "B"
    );

console.log(output);
//prints..
// [ { name: 'A', points: 1, type: 'typeA' },
//  { name: 'A', points: 3, type: 'typeB' },
//  { name: 'B', points: 1, type: 'typeA' },
//  { name: 'B', points: 2, type: 'typeB' } ]