重新排列数组以将特定元素放在给定索引处?

时间:2018-07-12 18:23:50

标签: javascript arrays

我有一个看起来像这样的数组:

var arr = [
   {name: 'Price'},
   {name: 'Sale'},
   {name: 'Shipping'},
   {name: 'Customer Rating'}
]

是否可以对数组进行排序,以使特定项位于给定索引处?例如,我一直希望“客户评分”位于索引1。

var arr = [
   {name: 'Price'},
   {name: 'Customer Rating'}
   {name: 'Sale'},
   {name: 'Shipping'}
]

ES6 One班轮解决方案的奖励积分!

4 个答案:

答案 0 :(得分:3)

查找名称为

的元素
let i = arr.findIndex(item => item.name === 'Customer Rating');

删除项目:

let [item] = arr.splice(i, 1);

插入项目:

arr.splice(1, 0, item);

不要将其放在一行:

arr.splice(1, 0, ...arr.splice(arr.findIndex(x => x.name=='Customer Rating'), 1));

let arr = [
   {name: 'Price'},
   {name: 'Sale'},
   {name: 'Shipping'},
   {name: 'Customer Rating'}
];

let i = arr.findIndex(item => item.name === 'Customer Rating');
let [item] = arr.splice(i, 1);
arr.splice(1, 0, item);
console.log(arr);

答案 1 :(得分:0)

使用mapfind

var arr = [
   {name: 'Price'},
   {name: 'Sale'},
   {name: 'Shipping'},
   {name: 'Customer Rating'}
];

var sorted = ['Price', 'Customer Rating', 'Sale', 'Shipping']
.map(e => arr.find(({name}) => name === e));

console.log(sorted);

答案 2 :(得分:0)

根据传入的名称查找对象,将其删除,然后将其重新添加到指定的索引中。您可以使用splice

let setIndex = (arr, index, namevalue) => {
 arr.splice(arr.findIndex( ({name}) => name == namevalue ), 1);
 arr.splice(index, 0, {name: namevalue});
 return arr;
}

var arr = [
   {name: 'Price'},
   {name: 'Sale'},
   {name: 'Shipping'},
   {name: 'Customer Rating'}
]

let setIndex = (arr, index, namevalue) => {
  arr.splice(arr.findIndex( ({name}) => name == namevalue ), 1);
  arr.splice(index, 0, {name: namevalue});
  return arr;
}

arr = setIndex(arr, 0, 'Customer Rating');

console.log(arr);

答案 3 :(得分:0)

您要查找的是交换而不是排序。

就像上面的答案一样,您需要先找到元素。

let i = arr.findIndex(item => item.name === 'Customer Rating');

然后跳过其余的答案。

Javascript swap array elements