分组或汇总Javascript数组

时间:2018-05-04 05:07:02

标签: javascript arrays json ecmascript-6

var json =
[
   {
      id: 11,
      name:"app1",
      family:"apps",
      caseID: 123,
      order:1
   },
   {
      id: 12,
      name:"app1",
      family:"apps",
      caseID: 123,
      order:2
   },
   {
      id: 13,
      name:"app1",
      family:"apps",
      caseID: 123,
      order:3
   },
   {
      id: 14,
      name:"app2",
      family:"tools",
      caseID: 129,
      order:1
   },
   {
      id: 15,
      name:"app2",
      family:"tools",
      caseID: 129,
      order:2
   },
   {
      id: 16,
      name:"app3",
      family:"utils",
      caseID: 120,
      order:1
   },
   {
      id: 17,
      name:"app3",
      family:"utils",
      caseID: 120,
      order:2
   },
      id: 18,
      name:"app3",
      family:"utils",
      caseID: 150,
      order:null
   }
  ] 

您好,我想通过最高的“order”键对上面的数组进行排序,并返回下面的过滤数组。公共密钥是caseID。此外,如果订单键为null,则返回它。 我已经搜索并测试了一些函数和循环,但似乎无法得到它。任何帮助都感激不尽。如果可能的话,我更喜欢es2015。 谢谢!

filtered = 
 [

  {
      id: 13,
      name:"app1",
      family:"apps",
      caseID: 123,
      order:3  
   },
   {
      id: 15,
      name:"app2",
      family:"tools",
      caseID: 129,
      order:2
   },
   {
      id: 17,
      name:"app3",
      family:"utils",
      caseID: 120,
      order:2
   },
   {
      id: 18,
      name:"app3",
      family:"utils",
      caseID: 150,
      order:null
   }
  ]

7 个答案:

答案 0 :(得分:2)

我首先要摆脱欺骗。您可以使用reduce()执行此操作并指定一个键入caseID的对象。您可以同时避免使用比您已经看到的order更小的任何对象。然后,您可以获取该散列的值,该散列将是caseID上的唯一对象,并按照您通常的方式对它们进行排序。例如:

var json = [{   "id": 11,   "name":"app1",   "family":"apps",   "caseID": 123,   "order":1},{   "id": 12,   "name":"app1",   "family":"apps",   "caseID": 123,   "order":2},{   "id": 13,   "name":"app1",   "family":"apps",   "caseID": 123,   "order":3},{   "id": 14,   "name":"app2",   "family":"tools",   "caseID": 129,   "order":1},{   "id": 15,   "name":"app2",   "family":"tools",   "caseID": 129,   "order":2},{   "id": 16,   "name":"app3",   "family":"utils",   "caseID": 120,   "order":1},{   "id": 17,   "name":"app3",   "family":"utils",   "caseID": 120,   "order":2},{   "id": 18,   "name":"app3",   "family":"utils",   "caseID": 150,   "order":null},] 

// get just the filtered items based on caseID
// picking out only the largest
let filtered = json.reduce((a,c) => {
      if (!a[c.caseID] || a[c.caseID]['order'] < c.order) a[c.caseID] = c
      return a
  }, {})

// basic sort
let result = Object.values(filtered).sort((a,b) => b.order - a.order)
console.log(result)

答案 1 :(得分:2)

如果caseID更高,您可以使用order哈希表并覆盖以后找到的结果:

  const result = [], hash = {};

  for(const el in json) {
   const exists = hash[el.caseId];
   if(exists) {
     if(el.order > exists.order)
       Object.assign(exists, el);
   } else {
       result.push(hash[el.caseId] = {...el});
   }
 }

答案 2 :(得分:0)

您可以尝试以下

方式

  1. 创建一个对象,其中唯一的案例ID为关键,而值为最高订单的项目
  2. 根据订单排序
  3. &#13;
    &#13;
    // Code goes here
    
    var json = [{"id":11,"name":"app1","family":"apps","caseID":123,"order":1},{"id":12,"name":"app1","family":"apps","caseID":123,"order":2},{"id":13,"name":"app1","family":"apps","caseID":123,"order":3},{"id":14,"name":"app2","family":"tools","caseID":129,"order":1},{"id":15,"name":"app2","family":"tools","caseID":129,"order":2},{"id":16,"name":"app3","family":"utils","caseID":120,"order":1},{"id":17,"name":"app3","family":"utils","caseID":120,"order":2},{"id":18,"name":"app3","family":"utils","caseID":150,"order":null}];
      
      
      var map = {};
    
      // Create a map of unique case ID's with highest order
      json.forEach((item) => {
        if(map[item.caseID]) {
            if(map[item.caseID].order < item.order) {
              map[item.caseID] = item;
            }
        } else {
          map[item.caseID] = item;
        }
      });
      
      // Sorting the array based on order
      var result = Object.values(map).sort((a,b) => b.order-a.order);
      console.log(result);
      
    &#13;
    &#13;
    &#13;

答案 3 :(得分:0)

在ES6中:

    private void btn_LoadFile_Click(object sender, EventArgs e)
    {
        OpenFileDialog fdlg = new OpenFileDialog();
        if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            System.IO.StreamReader sr = new
            System.IO.StreamReader(fdlg.FileName);

            string[] lines = sr.ReadToEnd().Split('\n');
            PrintText(tb_SerialNo, lines[0]);
            PrintText(tb_TypeNo , lines[1]);
            PrintText(tb_TestEngineer, lines[2]);
            PrintText(tb_Date, lines[3]);
            PrintText(tb_Test1, lines[4]);
            PrintText(tb_Test2, lines[5]);
        }

    }
    private void PrintText(TextBox control, string line)
    {
        var splitline = line.Split('=');
        control.Text = splitline[1];
    }

Example

在ES5中:

json.sort((a, b) => a.caseID > b.caseID);
let bad_order = json.filter(v => v.order === null);
let good_order = json.filter(v => v.order !== null);

Example

答案 4 :(得分:0)

使用reduce方法创建一个对象,其中的键将是caseID。创建对象时,检查订单的值是否大于或等于当前订单的值。如果是当前的订单值。 value小于新值,将其替换为新值。

然后使用Object.values(object)从对象

创建值数组

&#13;
&#13;
var json = [{
    "id": 11,
    "name": "app1",
    "family": "apps",
    "caseID": 123,
    "order": 1
  },
  {
    "id": 12,
    "name": "app1",
    "family": "apps",
    "caseID": 123,
    "order": 2
  },
  {
    "id": 13,
    "name": "app1",
    "family": "apps",
    "caseID": 123,
    "order": 3
  },
  {
    "id": 14,
    "name": "app2",
    "family": "tools",
    "caseID": 129,
    "order": 1
  },
  {
    "id": 15,
    "name": "app2",
    "family": "tools",
    "caseID": 129,
    "order": 2
  },
  {
    "id": 16,
    "name": "app3",
    "family": "utils",
    "caseID": 120,
    "order": 1
  },
  {
    "id": 17,
    "name": "app3",
    "family": "utils",
    "caseID": 120,
    "order": 2
  }, {
    "id": 18,
    "name": "app3",
    "family": "utils",
    "caseID": 150,
    "order": null
  }
]

var m = json.reduce(function(acc, curr, index) {
  if (acc[curr['caseID']] === undefined) {
    acc[curr['caseID']] = curr;

  } else {
    if (acc[curr['caseID']].order < curr.order) {
      acc[curr['caseID']] = curr;
    }
  }
  return acc;
}, {})
console.log(Object.values(m))
&#13;
&#13;
&#13;

答案 5 :(得分:0)

这可以帮助您过滤对象数组。

            var filteredMap = {};
            json.forEach(function (item) {
                filteredMap[item.caseID] = item;
            });
            var filteredArray = [];
            for (var key in filteredMap) {
                filteredArray.push(filteredMap[key]);
            }
            console.log(JSON.stringify(filteredArray));

答案 6 :(得分:0)

按顺序和caseID排序,然后按caseID过滤,这是代码:

var json =
[
   {
      id: 11,
      name:"app1",
      family:"apps",
      caseID: 123,
      order:1
   },
   {
      id: 12,
      name:"app1",
      family:"apps",
      caseID: 123,
      order:2
   },
   {
      id: 13,
      name:"app1",
      family:"apps",
      caseID: 123,
      order:3
   },
   {
      id: 14,
      name:"app2",
      family:"tools",
      caseID: 129,
      order:1
   },
   {
      id: 15,
      name:"app2",
      family:"tools",
      caseID: 129,
      order:2
   },
   {
      id: 16,
      name:"app3",
      family:"utils",
      caseID: 120,
      order:1
   },
   {
      id: 17,
      name:"app3",
      family:"utils",
      caseID: 120,
      order:2
   }, {
      id: 18,
      name:"app3",
      family:"utils",
      caseID: 150,
      order:null
   }
 ]
var obj = {}
var arr = json.sort(function(a, b) {
  return b.order - a.order
}).sort(function(a, b) {
  return a.caseId - b.caseId
}).filter(function(item, index, array){
  return obj.hasOwnProperty(item.caseID) ? false : (obj[item.caseID] = true)
})
console.log(arr)

演示:http://jsbin.com/qabehorike/edit?js,console,output