JavaScript将两个多维数组合并为唯一数组

时间:2020-06-21 16:31:27

标签: javascript ecmascript-6 merge lodash unique

我正在尝试对看起来像这样的数据进行排序:

{
    "Params": [
        ["section", "North"],
        ["monitor", "Single Monitor"],
        ["section", "North"],
        ["monitor", "Dual Monitor"]
    ]
}

变成这样的东西:

{
    "section": [
        "North"
    ],
    "monitor": [
        "Single Monitor",
        "Dual Monitor"
    ]
}

但是我目前遇到问题,我尝试了一些不同的事情,例如在循环中将数组连接在一起,甚至每次使用lodash的uniq函数时,但是每次得到不期望的结果时。

在此先感谢您的帮助

4 个答案:

答案 0 :(得分:2)

您可以使用array.reduce聚合数组数组:

let obj = {
    "Params": [
        ["section", "North"],
        ["monitor", "Single Monitor"],
        ["section", "North"],
        ["monitor", "Dual Monitor"]
    ]
}

let result = obj.Params.reduce((acc,cur) => {
   let [key,value] = cur;
   if(!acc[key]){
      acc[key] = [];
   }
   if(!acc[key].includes(value)){
      acc[key].push(value);
   }
   return acc;
}, {});

console.log(result);

答案 1 :(得分:0)

需要在此处进行操作数。您可以使用reduce来分组关键数据。由于您只有键值对数组格式,因此在reduce中,我用[k,v]来表示键和值来对其进行了结构分解。然后,要删除重复的值,我使用了Set

var data={
    "Params": [
        ["section", "North"],
        ["monitor", "Single Monitor"],
        ["section", "North"],
        ["monitor", "Dual Monitor"]
    ]
};

var result = data.Params.reduce((a,[k, v])=>(a[k] = [...(a[k] || []), v], a[k] = [...new Set(a[k])], a),{});

console.log(result);

答案 2 :(得分:0)

您可以使用_.groupBy()_.head()(每对的第一项)对项目进行分组。然后使用_.mapValues()迭代每个组,将其映射以获取_.last()项,并使用_.uniq()来获取唯一值:

const data = {"Params":[["section","North"],["monitor","Single Monitor"],["section","North"],["monitor","Dual Monitor"]]};

const result = _.mapValues(
  _.groupBy(data.Params, _.head), // group by the first item
  g => _.uniq(_.map(g, _.last)) // map each group to the last item, and get unique values
);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

使用lodash lodash / fp,您可以使用_.flow()生成一个功能相同的函数:

const { flow, groupBy, head, mapValues, map, last, uniq } = _;

const fn = flow(
  groupBy(head),
  mapValues(flow(
    map(last),
    uniq
  ))
);

const data = {"Params":[["section","North"],["monitor","Single Monitor"],["section","North"],["monitor","Dual Monitor"]]};

const result = fn(data.Params);

console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

答案 3 :(得分:0)

您可以将reduce()方法转换为groupBy功能,如下所示

let obj = {
  "Params": [
    ["section", "North"],
    ["monitor", "Single Monitor"],
    ["section", "North"],
    ["monitor", "Dual Monitor"]
  ]
};

const res = obj.Params.reduce((acc, [key, val]) => {
  acc[key] = acc[key] || [];
  if (!acc[key].includes(val)) {
    acc[key].push(val);
  }
  return acc;
}, {});
console.log(res);

相关问题