Sort by index an array

This question already has an answer here:

  • Sort array of objects by string property value in JavaScript 33 answers
  • Sorting an array of JavaScript objects 24 answers

  • 首先对列表进行排序,通过自定义排序函数来比较索引,然后映射。

        var exemples =  [
                {
                    'name'     : 'd',
                    'index'    : 3
                },
                {
                    'name'     : 'c',
                    'index'     : 2
                },
                {
                    'name'     : 'a',
                    'index'    : 0
                },
                {
                    'name'     : 'b',
                    'index'    : 1
                }
            ];
    
          const list = exemples.sort((a,b) => a.index - b.index).map((exemple, index, array) => exemple.name)
    
          console.log(list)

    You don't need to sort and filter. Use Array#reduce . In just one iteration you can get the sorted elements. This is more efficient than first sorting and then filtering. This would give you O(n) solution. See below as an example.

    var exemples = [{
        'name': 'd',
        'index': 3
      },
      {
        'name': 'c',
        'index': 2
      },
      {
        'name': 'a',
        'index': 0
      },
      {
        'name': 'b',
        'index': 1
      }
    ];
    
    var ans = exemples.reduce(function (r,v) {
      r[v.index] = v.name;
      return r;
    }, []);
    
    console.log(ans);

    You can sort the array before you map it. Here is an example:

    var exemples =  [{'name'     : 'd','index'    : 3},{'name'     : 'c','index'     : 2},{'name'     : 'a','index'    : 0},{'name'     : 'b','index'    : 1}];
    
    const list = exemples.sort((v1, v2) => v1.index - v2.index).map((v) => v.name);
    console.log(list)
    链接地址: http://www.djcxy.com/p/19340.html

    上一篇: 根据条件对对象组进行排序

    下一篇: 按数组索引排序