Javascript:确定数组中的重复对象并返回它们的数组

时间:2017-01-18 13:47:23

标签: javascript arrays

我有一个对象数组

[
 {
    classname: ".icon"
    data : "12"
    },
    {
    classname: ".icon1"
    data : "34"
    },
    {
    classname: ".icon2"
    data : "56"
    },
    {
    classname: ".icon"
    data : "78"
    },
    {
    classname: ".icon1"
    data : "90"
    },
    {
    classname: ".icon1"
    data : "AB"
    }
]

我想返回按副本分组的数组数组,如此

[
{
classname: ".icon"
data : "12"
},
{
classname: ".icon"
data : "78"
}
]

[
{
classname: ".icon1"
data : "34"
},
{
classname: ".icon1"
data : "90"
},
{
classname: ".icon1"
data : "AB"
}
]

我可以使用lodash以及本机JavaScript。 重要:必须在返回的数组数组中维护其原始出现的顺序。 我正在键入属性名称'classname'

1 个答案:

答案 0 :(得分:2)

您可以使用reduce()

执行此操作

var data = [{"classname":".icon","data":"12"},{"classname":".icon1","data":"34"},{"classname":".icon2","data":"56"},{"classname":".icon","data":"78"},{"classname":".icon1","data":"90"},{"classname":".icon1","data":"AB"}]

var obj = {}
var result = data.reduce(function(r, e) {
  if (!obj[e.classname]) {
    obj[e.classname] = []
    r.push(obj[e.classname])
  }
  obj[e.classname].push(e)
  return r;
}, [])


console.log(result)