【问题标题】:Sort by index an array [duplicate]按索引排序数组[重复]
【发布时间】:2017-11-01 11:33:02
【问题描述】:

看下面的代码:

    var exemples =  [
            {
                'name'     : 'd',
                'index'    : 3
            },
            {
                'name'     : 'c',
                'index'     : 2
            },
            {
                'name'     : 'a',
                'index'    : 0
            },
            {
                'name'     : 'b',
                'index'    : 1
            }
        ];

      const list = exemples.map((exemple, index, array) => exemple.name)

      console.log(list)

它给了我那个数组:

["d", "c", "a", "b"]

我想尊重索引并得到这样的结果:

["a", "b", "c", "d"]

听起来是个基本问题,但我需要您的帮助。谢谢。

【问题讨论】:

    标签: javascript arrays indexing


    【解决方案1】:

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

        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)

    【讨论】:

      【解决方案2】:

      您可以在映射之前对数组进行排序。 这是一个例子:

      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)

      【讨论】:

        【解决方案3】:

        您不需要排序和过滤。 使用Array#reduce。 只需一次迭代,您就可以获得已排序的元素。这比先排序再过滤更有效。这将为您提供 O(n) 解决方案。请参阅下面的示例。

        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);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-22
          • 1970-01-01
          • 2018-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-07
          相关资源
          最近更新 更多