我有一个这样的对象:
var data = [
{ id: "fmgbwe45", age: 24, gender: "male" },
{ id: "kjregh23", age: 27, gender: "female" },
{ id: "kjfdhg87", age: 30, gender: "male" },
{ id: "lsdjfk43", age: 10, gender: "female" },
]
我想对对象进行排序,这是我的 预期产出:
var data = [
{ id: "kjfdhg87", age: 30, gender: "male" }, //only one record will match in my sort
{ id: "fmgbwe45", age: 24, gender: "male" },
{ id: "kjregh23", age: 27, gender: "female" },
{ id: "lsdjfk43", age: 10, gender: "female" },
]
我试过这个:
$scope.sort_by = function (newSortingOrder) {
var stringToFilter = newSortingOrder.toString(); //this holds 'kjfdhg87'
var obj = data.sort(function(o) { return o.id - stringToFilter; });
var finalObj = [obj];
sortedData = finalObj;
console.log(sortedData ); //sorting is not working as expected where im doing wrong.
}
答案 0 :(得分:5)
由于您只是将一个项目移到顶部,我将只使用splice()
和unshift()
项目:
var data = [
{ id: "fmgbwe45", age: 24, gender: "male" },
{ id: "kjregh23", age: 27, gender: "female" },
{ id: "kjfdhg87", age: 30, gender: "male" },
{ id: "lsdjfk43", age: 10, gender: "female" },
]
data.forEach(function(item,i){
if(item.id === "kjfdhg87"){
data.splice(i, 1);
data.unshift(item);
}
});
console.log(data);
答案 1 :(得分:3)
这是另一种不变的方法。我只是为Person定义使用TypeScript,但除此之外,只是ES6。
基本上,我们只需要:
movePersonInArray(person: Person, arrayOfPersons: Person[]): Person[] {
// remove the item from the array
const filterArrayOfPersons = arrayOfPersons.filter((p: Person) => p.id !== person.id);
// add it at the beginning
return [{ ...person }, ...filterArrayOfPersons];
}
如果您不介意混淆,可以避免使用 spread 运算符,而使用 unshift 。我特别不喜欢将使数组变异的函数与不使数组变异的函数混合在一起,但是在某些情况下,您可能会获得一些性能提升。例如,对于一个很长的数组,对原始方法的以下更改将在保持可读性的同时加快处理速度。
// add it at the beginning
filterArrayOfPersons.unshift({...person});
return filterArrayOfPersons;
这两种方法都不会变异 arrayOfPersons 数组,而是返回具有更改的副本。 在这里您可以了解有关数组突变方法的更多信息 https://doesitmutate.xyz/
PS。 Person 类型可以是这样的:
export interface Person {
id: string;
name: string;
age: number;
}
和平!
答案 2 :(得分:2)
您可以使用unshift
方法。
var data = [
{ id: "fmgbwe45", age: 24, gender: "male" },
{ id: "kjregh23", age: 27, gender: "female" },
{ id: "kjfdhg87", age: 30, gender: "male" },
{ id: "lsdjfk43", age: 10, gender: "female" },
]
var stringToFilter = 'kjfdhg87'; //this holds 'kjfdhg87'
data.unshift(data.splice(data.findIndex(item => item.id === stringToFilter), 1)[0])
console.log(data);