push() won't work as expected in reduce()

后端 未结 4 437
悲&欢浪女
悲&欢浪女 2021-01-17 08:48

Why doesn\'t a.push(b) work in my Array.reduce()? a=a.push(b) where b is a string, turns a to an integer.?!



        
相关标签:
4条回答
  • 2021-01-17 09:05

    Please note that this structure you provide is not clear enough

    I would use instead an array of objects each having a name and a frecuency

    var frequencies = [{name : "mats", frecuency : 1},
                       {name : "john", frecuency: 3},
                       {name : "johan", frecuency: 2},
                       {name : "jacob", frecuency: 3}];
    

    Then you can use a filter operation and map to get what you need

    var max = Math.max.apply(Math, frequencies.map(function(o){return o.frecuency;}));
    var maxElems = frequencies.filter(function(a){return a.frecuency == max}).map(function(a){return a.name;});
    

    maxElems will give you the names of the people with higher frecuency

    0 讨论(0)
  • 2021-01-17 09:12

    Since push() returns the new length of the array, you're assigning the length to a. Instead of a conditional operator, use an if statement.

    var winner = objKeys.reduce((a, b) => {
        if (frequency[b] === highestVal) {
            a.push(b);
        }
        return a;
    }, []);
    
    0 讨论(0)
  • 2021-01-17 09:16

    Building on the excellent answer by @Alexander Moiseyev.

    You can avoid setting and mutating both variables a and winner by doing the following:

    return objKeys.reduce((acc, val) =>
        frequency[val] === highestVal 
          ? [...acc, val] 
          : acc
    ,[])
    

    note: for clarity I have explicitly declared the accumulator and value in this reduce method.

    0 讨论(0)
  • 2021-01-17 09:23

    The push() returns the new length. You can use ES2015 spread syntax:

    
    var winner = objKeys.reduce((a, b)=> {
        a = (frequency[b] === highestVal)? [...a, b] : a;
        return a
    }, []);
    
    
    0 讨论(0)
提交回复
热议问题