最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Lodash's unionBy and merge nested arrays? - Stack Overflow

programmeradmin0浏览0评论

Im looking to merge/bine objects in an array each with a series of nested arrays. I want to merge the objects based on a specific key (here label[1]). I can use Lodash and unionBy to filter out dublicates by label[1], but how do i keep the values from the filtered items?

The array can look like this:

var arr = [{
    "label": ['item', 'private'],
    "values": [1, 2, 3]
  },
  {
    "label": ['item', 'private'],
    "values": [1, 2, 3, 6]
  },
  {
    "label": ['item', 'work'],
    "values": [1, 2, 8, 9]
  },
  {
    "label": ['item', 'private'],
    "values": [1, 2, 4, 5]
  },
  {
    "label": ['item', 'school'],
    "values": [1, 2, 7]
  }
];

And the desired output is:

var arr = [{
  "label": ["item", "private"],
  "values": [1, 2, 3, 4, 5, 6 ]
}, {
  "label": ["item", "work"],
  "values": [1, 2, 8, 9]
}, {
  "label": ["item", "school"],
  "values": [1, 2, 7]
}]

Here's a sample which is only half way there.

var arr = [
  { label: ['item','private'], values: [1,2,3] },
  { label: ['item','private'], values: [1,2,3,6] },
  { label: ['item','work'], values: [1,2,8,9] },
  { label: ['item','private'], values: [1,2,4,5] },
  { label: ['item','school'], values: [1,2,7] }
];

var result = _.unionBy(arr, "label[1]");

console.log(result);
<script src=".js/4.17.11/lodash.js"></script>

Im looking to merge/bine objects in an array each with a series of nested arrays. I want to merge the objects based on a specific key (here label[1]). I can use Lodash and unionBy to filter out dublicates by label[1], but how do i keep the values from the filtered items?

The array can look like this:

var arr = [{
    "label": ['item', 'private'],
    "values": [1, 2, 3]
  },
  {
    "label": ['item', 'private'],
    "values": [1, 2, 3, 6]
  },
  {
    "label": ['item', 'work'],
    "values": [1, 2, 8, 9]
  },
  {
    "label": ['item', 'private'],
    "values": [1, 2, 4, 5]
  },
  {
    "label": ['item', 'school'],
    "values": [1, 2, 7]
  }
];

And the desired output is:

var arr = [{
  "label": ["item", "private"],
  "values": [1, 2, 3, 4, 5, 6 ]
}, {
  "label": ["item", "work"],
  "values": [1, 2, 8, 9]
}, {
  "label": ["item", "school"],
  "values": [1, 2, 7]
}]

Here's a sample which is only half way there.

var arr = [
  { label: ['item','private'], values: [1,2,3] },
  { label: ['item','private'], values: [1,2,3,6] },
  { label: ['item','work'], values: [1,2,8,9] },
  { label: ['item','private'], values: [1,2,4,5] },
  { label: ['item','school'], values: [1,2,7] }
];

var result = _.unionBy(arr, "label[1]");

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

Any ideas?

Thanks Lasse

Share Improve this question asked Nov 20, 2018 at 14:52 Lasse van den Bosch ChristenseLasse van den Bosch Christense 811 silver badge6 bronze badges 1
  • You say you want to group by label[1], but what happens if the other parts of the label differ? which one should be used in the grouped result? – tokland Commented Oct 13, 2022 at 22:40
Add a ment  | 

3 Answers 3

Reset to default 3

I'd write:

const arr2 = _(arr)
    .groupBy(obj => obj.label[1])
    .values()
    .map(objs => ({
        label: objs[0].label,
        values: _(objs).flatMap("values").uniq().value(),
    }))
    .value()

Not sure how to do this with lodash but I don't think unionBy is the method to do this anyway.

Here is how you can group by label using lodash and then reduce the groups into one value to merge the items of a group.

const arr = [{"label":["item","private"],"values":[1,2,3]},{"label":["item","private"],"values":[1,2,3,6]},{"label":["item","work"],"values":[1,2,8,9]},{"label":["item","private"],"values":[1,2,4,5]},{"label":["item","school"],"values":[1,2,7]}];

console.log(
  Object.values(
    _.groupBy(arr, (item) => item.label.join()),//use lodash group by
  ).map((
    group, //now we have array of array of groups
  ) =>
    group
      .reduce((result, item) => ({
        //reduce a group to one object
        label: result.label, //set label
        values: [
          //set values with unique values of all items
          ...new Set(
            (result.values || []).concat(item.values || []),
          ),
        ],
      })),
  ),
);
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.11/lodash.js"></script>

You could also do something like this via lodash:

var arr = [{ "label": ['item', 'private'], "values": [1, 2, 3] }, { "label": ['item', 'private'], "values": [1, 2, 3, 6] }, { "label": ['item', 'work'], "values": [1, 2, 8, 9] }, { "label": ['item', 'private'], "values": [1, 2, 4, 5] }, { "label": ['item', 'school'], "values": [1, 2, 7] } ]

const merge = arr => _.reduce(arr, (r,c) => _.union(r, c.values), [])
const result = _(arr).groupBy('label')
 .entries()
 .reduce((r,[k,v]) => (r.push({ label: k.split(','), values: merge(v) }), r), [])

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

The idea is first to group by via _.groupBy and then get the entries (via _.entries) so you can form the desired output via _.reduce. _.union we use to merge the values arrays as part of the final reduce.

Here is the ES6 implementation:

var arr = [{ "label": ['item', 'private'], "values": [1, 2, 3] }, { "label": ['item', 'private'], "values": [1, 2, 3, 6] }, { "label": ['item', 'work'], "values": [1, 2, 8, 9] }, { "label": ['item', 'private'], "values": [1, 2, 4, 5] }, { "label": ['item', 'school'], "values": [1, 2, 7] } ]

const mrg = arr => Array.from(new Set(arr.reduce((r,c) => [...r, ...c.values], [])))
const grp = (arr, k) => arr.reduce((r,c) => (r[c[k]] = [...r[c[k]] || [], c], r), {}) 
const result = Object.entries(grp(arr, 'label'))
  .reduce((r,[k,v]) => (r.push({ label: k.split(','), values: mrg(v) }), r), [])

console.log(result)

发布评论

评论列表(0)

  1. 暂无评论