在 JavaScript 中按数组索引排序

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 12:28:17

假设我们有以下对象数组 −

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

我们需要编写一个 JavaScript 函数来接收一个这样的数组。

该函数应根据对象的 index 属性按升序对该数组进行排序。

然后,该函数应将排序后的数组映射到一个字符串数组,其中每个字符串都是对象对应的 name 属性值。

因此,对于上述数组,最终输出应如下所示 −

const output = ["a", "b", "c", "d"];

示例

其代码为 −

const arr = [
   {
      'name' : 'd',
      'index' : 3
   },
   {
      'name' : 'c',
      'index' : 2
   },
   {
      'name' : 'a',
      'index' : 0
   },
   {
      'name' : 'b',
      'index' : 1
   }
];
const sortAndMap = (arr = []) => {
   const copy = arr.slice();
   const sorter = (a, b) => {
      return a['index'] - b['index'];
   };
   copy.sort(sorter);
   const res = copy.map(({name, index}) => {
      return name;
   });
   return res;
};
console.log(sortAndMap(arr));

输出

控制台中的输出将是 −

[ 'a', 'b', 'c', 'd' ]

相关文章


有用资源