Javascript删除多重阵列中的冗余

时间:2018-04-05 08:23:42

标签: javascript html multidimensional-array

需要帮助处理javascript中的多维数组。 样本数组如下: 开始,结束时间,名称

[04/04/2017 11:00:42,04/04/2018 12:15:37,Nic],
[04/04/2017 11:00:42,04/04/2018 12:16:58,Nic]

结果如下:

[04/04/2017 11:00:42,04/04/2018 12:16:58,Nic]

我们需要比较2索引第一索引和最后索引,如果匹配则秒索引作为结束时间将从最后一个数组。

下面的示例代码删除多余的。但是,当需要比较多于1个索引并将最后一个记录作为结果时,会混淆。

var compare = new Array();var result = new Array();
for (var y = 0; y < list.size(); y++) {
    if(list.indexOf(list[y][0]) < 0){
        compare.push(listdetails[y][0]);
        result.push(listdetails[y]);
    }
}

任何人都可以提供帮助吗?

2 个答案:

答案 0 :(得分:1)

一种选择是使用reduce将数据汇总到一个对象中。使用Object.values将对象转换为数组。

&#13;
&#13;
var arr = [
  ['04/04/2017 11:00:42', '04/04/2018 12:15:37', 'Nic'],
  ['04/04/2017 11:00:42', '04/04/2018 12:16:58', 'Nic'],
  ['04/04/2017 11:00:42', '04/04/2018 12:16:50', 'Apple']
];

var result = Object.values(arr.reduce((c, v) => Object.assign(c, {[v[0]+v[2]]: v}), {}));

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用reduceObject.values

//method to get the unique key out of an array item which is also an array
var getKey = ( arr ) => arr[0] + arr[2];
var output = Object.values( arr.reduce( (acc, c) => ( 
     acc[getKey(c)] = c,  //set the latest value with the same key to accumulator
     acc ) , //return the accumulator
{})); //initialize accumulator to {} 

<强>演示

&#13;
&#13;
var arr = [
  ["04/04/2017 11:00:42", "04/04/2018 12:15:37", "Nic"],
  ["04/04/2017 11:00:42", "04/04/2018 12:16:58", "Nic"]
];

var getKey = ( arr ) => arr[0] + arr[2];
var output = Object.values(arr.reduce((acc, c) => (acc[getKey(c)] = c, acc), {}));

console.log( output );
&#13;
&#13;
&#13;