在JavaScript数组中组合重复值

时间:2018-05-28 13:17:03

标签: javascript arrays json

我有一个包含一些键/值的json对象其中一个值是一个数组我希望将所有记录的数组的值组合起来,这些数据具有相同的键,这是我的Json对象

data= 
[
 {"key":11,"numbers":[555,556,557]},
 {"key":22,"numbers":[444,772,995,667]},
 {"key":11,"numbers":[223,447]},
 {"key":45,"numbers":[999,558,367]}
]

我希望得到的结果是这样的

data= 
[
   {"key":11,"numbers":[555,556,557,223,447]},
   {"key":22,"numbers":[444,772,995,667]},
   {"key":45,"numbers":[999,558,367]}
]

我试过但我不知道如何缓存当前匹配行的值并尝试找到另一个匹配值这是我的代码

data= 
[
 {"key":11,"numbers":[555,556,557]},
 {"key":22,"numbers":[444,772,995,667]},
 {"key":11,"numbers":[223,447]},
 {"key":45,"numbers":[999,558,367]}
];
function findDuplicates(data) {

 let result = [];

data.forEach(function(element, index) {

if (data.indexOf(element, index + 1) > -1) { 
  if (result.indexOf(element) === -1) {

    result.push(element.numbers.concat(data.indexOf(element, index + 1));
  }
}
});

return result;
}

console.log( findDuplicates(data) ); 

1 个答案:

答案 0 :(得分:4)

您可以使用<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_URI} !^public RewriteRule ^.*$ https://%{HTTP_HOST}/public%{REQUEST_URI} [L,R=301] </IfModule> 将数组分组到一个对象中。使用SELECT num FROM (SET @row_number = 0; SELECT (@row_number:=@row_number + 1) AS num, id FROM tickets order by `priority` ASC, `created` desc) as tmp_table WHERE id = 6; 合并数组。使用reduce将对象转换为数组。

&#13;
&#13;
concat
&#13;
&#13;
&#13;