如何在javascript中比较相同的数组

时间:2022-02-12 13:45:42

How to compare identical arrays in Javascript

如何在Javascript中比较相同的数组

MasterHash has Key with Array of values.

MasterHash具有值数组的键。

Name1 : [1,10],
Name2 : [2,2134],
Name3 : [3,512],
Name4 : [4,771],
Name5 : [3,555],
Name6 : [1,10],
Name7 : [5, 8888],
Name8 : [1,10],
Name9 : [3,555]

Want to get output as

想要输出为

1_10 : Name1, Name6, Name8
3_555: Name5, Name9

1 个解决方案

#1


0  

You could do this with Object.keys() and reduce() and return object.

您可以使用Object.keys()和reduce()并返回对象。

var data = {Name1 : [1,10],Name2 : [2,2134],Name3 : [3,512],Name4 : [4,771],Name5 : [3,555],Name6 : [1,10],Name7 : [5, 8888],Name8 : [1,10],Name9 : [3,555]}

var o = {}
var result = Object.keys(data).reduce(function(r, e) {
  var k = data[e].join('_');
  o[k] = (o[k] || []).concat(e);
  if(o[k].length > 1) r[k] = o[k];
  return r;
}, {});


document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';

#1


0  

You could do this with Object.keys() and reduce() and return object.

您可以使用Object.keys()和reduce()并返回对象。

var data = {Name1 : [1,10],Name2 : [2,2134],Name3 : [3,512],Name4 : [4,771],Name5 : [3,555],Name6 : [1,10],Name7 : [5, 8888],Name8 : [1,10],Name9 : [3,555]}

var o = {}
var result = Object.keys(data).reduce(function(r, e) {
  var k = data[e].join('_');
  o[k] = (o[k] || []).concat(e);
  if(o[k].length > 1) r[k] = o[k];
  return r;
}, {});


document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4) + '</pre>';