代码之家  ›  专栏  ›  技术社区  ›  Bas

javascript按给定键对json数组进行排序[duplicate]

  •  0
  • Bas  · 技术社区  · 4 年前

    鉴于

    let jsons = [
        {
        "id": 10
        ...
      }, 
        {
        "id": 4
        ...
      }, 
        {
        "id": 1
        ...
      }, 
      ...
    
    
    ]
    

    我希望JSON按id排序,例如。

    let jsons = [
        {
          "id": 1
          ...
        }, 
        {
          "id": 2
          ...
        }, 
        {
          "id": 3
          ...
        }, 
        ...
    ]
    

    我就是这么做的(但效率极低)

    let jsons = [
        {
        "id": 10
        
      }, 
        {
        "id": 4
        
      }, 
        {
        "id": 1
        
      }, 
      
    ]
    
    let new_list = []
    length = jsons.length
    for(let i = 0; i < length; i++) {
      let index = 0
      let cur_lowest = 50000 // not sure how to get an infinite upper_bound
      for(let j = 0; j < jsons.length; j++) {
        if(jsons[j].id <= cur_lowest) {
            cur_lowest = jsons[j].id
          index = j
        }
      }
      new_list.push(jsons[index])
      jsons.splice(index, 1)
    }
    console.log(new_list);
    

    所以我在这里做到了 https://jsfiddle.net/xceybhLg/5/

    但有更简单的方法吗?最好是像排序功能一样,我认为它可以附加在键上,但阅读文档时我并不真正理解它

    1 回复  |  直到 4 年前
        1
  •  0
  •   Nitheesh    4 年前

    为什么不能使用一个简单的排序函数来接受一个列表和一个要对其执行排序操作的键呢。

    let jsons = [
      { "id": 10 },
      { "id": 4 },
      { "id": 1 },
    ];
    function sortList(list, key) {
      return list.sort((a, b) => a[key] - b[key]);
    }
    const new_list = sortList(jsons, 'id');
    console.log(new_list);