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

lodash - How to remove duplicates objects from array in javascript? - Stack Overflow

programmeradmin1浏览0评论

In my code i have created one array called array1. In this array i have listed multiple objects. I want to filter out array1 objects values as unique and need to group ids with their respective values. I have added my code here,

Array1

var array1 = [
            {
                value:"A",
                id:1
            },
            {
                value:"B",
                id:1
            },
            {
                value:"C",
                id:2
            },
            {
                value:"B",
                id:5
            },
            {
                value:"A",
                id:2
            },
            {
                value:"A",
                id:1
            }
        ];

the result which i want,

[
            {
                group:"A",
                groupIds:[1, 2]
            },
            {
                group:"B",
                groupIds:[1, 5]
            },
            {
                group:"C",
                groupIds:[2]
            }
        ]

In my code i have created one array called array1. In this array i have listed multiple objects. I want to filter out array1 objects values as unique and need to group ids with their respective values. I have added my code here,

Array1

var array1 = [
            {
                value:"A",
                id:1
            },
            {
                value:"B",
                id:1
            },
            {
                value:"C",
                id:2
            },
            {
                value:"B",
                id:5
            },
            {
                value:"A",
                id:2
            },
            {
                value:"A",
                id:1
            }
        ];

the result which i want,

[
            {
                group:"A",
                groupIds:[1, 2]
            },
            {
                group:"B",
                groupIds:[1, 5]
            },
            {
                group:"C",
                groupIds:[2]
            }
        ]
Share Improve this question edited Dec 30, 2016 at 12:24 Andreyco 22.9k5 gold badges63 silver badges66 bronze badges asked Dec 30, 2016 at 11:56 SathyaSathya 1,7343 gold badges38 silver badges59 bronze badges 2
  • 2 Have you searched SO? There's some similar questions: stackoverflow./questions/24919074/…, stackoverflow./questions/12873228/javascript-group-by-array, stackoverflow./questions/14446511/… – Ricardo Pontual Commented Dec 30, 2016 at 12:01
  • I searched and tried too. But the result which i added in my question is not ing like that – Sathya Commented Dec 30, 2016 at 12:04
Add a ment  | 

6 Answers 6

Reset to default 4

In plain Javascript, you could use a hash table and Array#indexOf for unique values.

var array = [{ value: "A", id: 1 }, { value: "B", id: 1 }, { value: "C", id: 2 }, { value: "B", id: 5 }, { value: "A", id: 2 }, { value: "A", id: 1 }],
    grouped = array.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.value]) {
                hash[a.value] = { group: a.value, groupIds: [] };
                r.push(hash[a.value]);
            }
            if (hash[a.value].groupIds.indexOf(a.id) === -1) {
                hash[a.value].groupIds.push(a.id);
            }
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can use forEach() to group objects by values and Set() to remove duplicate ids from groupIds

var array1 = [{"value":"A","id":1},{"value":"B","id":1},{"value":"C","id":2},{"value":"B","id":5},{"value":"A","id":2},{"value":"A","id":1}]

var result = [];
array1.forEach(function(e) {
  if(!this[e.value]) (this[e.value] = {group: e.value, groupIds: []}) && result.push(this[e.value])
  this[e.value].groupIds = [...new Set(this[e.value].groupIds.concat(e.id))]
}, {})

console.log(result)

_.uniqBy(objects, function (object) {
  return object.id;
});

that will do :)

Using lodash:

_(array1)
  .uniqWith(_.isEqual)
  .groupBy('value')
  .map((v, k) => ({ group: k, groupIds: _.map(v, 'id')}))
  .value()
  • uniqWith() uses isEqual() to remove duplicates. You want to use this approach so that the id and the value props are pared.
  • groupBy() creates an object whose keys are the value property. Since there are three unique values in the initial array, this object should have three keys.
  • map() turns the object back into an array, with the expected group and groupIds properties.

use _.groupBy and _.mapValues to iterate object values

var res = _.chain(array1)
    .groupBy('value')
    .mapValues(function(val, key) {
        return {
            group: key,
            groupIds: _.chain(val).map('id').uniq().value()
        };
    })
    .values()
    .value();

Here's another in plain Javascript.

var hash = {}
array1.forEach( function(e) { 
    hash[e.value] = hash[e.value] || []; 
    if (hash[e.value].indexOf(e.id) == -1) { hash[e.value].push(e.id) }
})
var result = Object.keys(hash).map( function(key) { 
    return { group: key, groupIds: hash[key] } 
})
发布评论

评论列表(0)

  1. 暂无评论