过滤嵌套数组-JavaScript

时间:2018-10-11 08:23:00

标签: javascript multidimensional-array filter

我有一个嵌套数组,每个数组都有一个字符串和一个整数,某些数组中的字符串是相同的,但是我想过滤该数组,以便它只包含具有唯一名称且具有最高名称的嵌套数组价值观。这是我拥有和想要的东西的一个示例:

[['a', 1],['a', 2],['a', 3],['b',2],['b',5]]

我想做的是过滤,使其包含以下内容:

[['a', 3],['b', 5]]

当我查看过滤时,我最初尝试使用for循环和if语句,然后使用for循环和while语句来执行此操作,但是我不确定如何在将字符串保持最高的位置实现该方法值,请帮忙!!!!

5 个答案:

答案 0 :(得分:3)

您可以将Map用于第一个元素的分组,并通过检查存储的值来获取最大值。

var array = [['a', 1], ['a', 2], ['a', 3], ['b', 2], ['b', 5]],
    result = Array.from(
        array.reduce((m, [k, v]) => m.set(k, m.has(k) ? Math.max(v, m.get(k)) : v), new Map)
    );
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果您希望保留原始数组,则可以存储该数组而不是值,然后只获取地图的值。

var array = [['a', 1], ['a', 2], ['a', 3, 'bar'], ['b', 2], ['b', 5, 'foo']],
    result = Array.from(array
        .reduce(
            (m, a) => m.has(a[0]) && m.get(a[0])[1] > a[1] ? m : m.set(a[0], a),
            new Map
        )
        .values()
    );
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

这是使用reduceObject.keysmap的解决方案。

const data = [['a', 1],['a', 2],['a', 3],['b',2],['b',5]];

//in reducer we work with object instead of array
//efficient since we avoid doing an extra loop
const result = data.reduce((acc, cur)=>{

  //create variables from current array (ex: ['a', 1])
  const letter = cur[0];
  const value = cur[1];

  //Acc (accumulator) holds the highest values (ex {a: 1, b: 2} )
  //If the letter doesn't yet exist or if the cur value is higher we update the acc
  if(!acc[letter] || acc[letter] < value){
    acc[letter] = value;
  }
  
  return acc;
}, {});

//Not in the correct format, so we transform the result into the requested format
const final = Object.keys(result).map(key=>[key, result[key]]);

console.log(final);

答案 2 :(得分:0)

const data = [['a', 1],['a', 2],['a', 3],['b',2],['b',5]]
const buf = {}
data.map(arr => {
    if(!buf[arr[0]] || buf[arr[0]] < arr[1])
        buf[arr[0]] = arr[1]
})
const result = Object.keys(buf).map(k => [k, buf[k]]);
console.log(result)

答案 3 :(得分:0)

const obj = [['a', 1],['a', 2],['a', 3],['b',2],['b',5]].reduce((res, arr) => {
    res[arr[0]] = !res[arr[0]] ? arr[1] : Math.max(res[arr[0]], arr[1])
    return res
}, {})
const result = Object.keys(obj).map((key) => [key, obj[key]])

答案 4 :(得分:0)

const data = [['a', 1],['a', 2],['a', 3],['b',2],['b',5]];
var result = data.sort(function(a,b){
    return Math.max(b[1]-a[1]);
});
var new_data= result.slice(0,2);
console.log(new_data.reverse());