如何 concat() 多个数组并检查值是否已存在

Fon*_*nty 0 arrays typescript angular

我将多个数组连接到一个数组。这个效果很好

\n\n
this.facetsLocations = [].concat(\n                response.facets[\'134_locations\'].terms,\n                response.facets[\'135_locations\'].terms\n              );\n
Run Code Online (Sandbox Code Playgroud)\n\n

但输出不是我想要的。正如你所看到的,我有相同的术语,如“deutschland”,计数:6\n“deutschland”,计数:4 等等。

\n\n

结果应该是一个“deutschland”,计数 10\ni 想检查该值是否已存在并添加计数值。

\n\n
(11) [{\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}]\n0: {term: "deutschland", count: 6}\n1: {term: "basel", count: 3}\n2: {term: "osteuropa", count: 2}\n3: {term: "\xc3\xb6sterreich", count: 1}\n4: {term: "ungarn", count: 1}\n5: {term: "schweiz", count: 1}\n6: {term: "basel", count: 5}\n7: {term: "deutschland", count: 4}\n8: {term: "\xc3\xb6sterreich", count: 1}\n9: {term: "ungarn", count: 1}\n
Run Code Online (Sandbox Code Playgroud)\n

par*_*er9 5

concat()函数仅连接两个数组,即返回一个新数组,其中包含第一个和第二个(以及更多)数组中的所有元素。它不做任何其他事情,也不关心合并数组的内容,这应该是您的应用程序的逻辑。

实现您需要的一种方法是使用reduce()而不是concat(),如下所示:

// This is pretty much the same as doing concatenation your way
const terms = [
  ...response.facets['134_locations'].terms,
  ...response.facets['135_locations'].terms,
];

// using reducer on all terms
this.facetsLocations = Object.values(terms.reduce((acc, item) => {
  if (typeof acc[item.term] === 'undefined') {
    // set default value for each term as 0
    acc[item.term] = item;
  } else {
    // add to total count of each term
    acc[item.term].count += item.count;

    // potentially add logic to handle changing "selected" too...
  }

  return acc;
}, {}));
Run Code Online (Sandbox Code Playgroud)