Js中根据给定的输入对数组进行排序
Sort Array According to Giving input In Js
我有这样的数组:
Arr = [{name:"abc",age:1},{name:"a",age:4},{name:"ac",age:3},{name:"abc",age:2},{name:"abc",age:9}]
我想这样改:
[{name:"abc",age:1},{name:"abc",age:2},{name:"abc",age:9},{name:"a",age:4},{name:"ac",age:3}]
通过排序或交换。
试试这个
arr1.sort((a, b) => {
if(a.name.startsWith(b.name)) { return -1; }
if(a.name < b.name) { return -1; }
if(a.name > b.name) { return 1; }
return 0;
})
您可以使用 Map
收集相同命名的对象并取回扁平值。
此方法保持 name
的给定顺序并将该对象同名组合在一起。
var array = [{ name: "abc", age: 1 }, { name: "a", age: 4 }, { name: "ac", age: 3 }, { name: "abc", age: 2 }, { name: "abc", age: 9 }];
array = Array
.from(array
.reduce((m, o) => m.set(o.name, [...(m.get(o.name) || []), o]), new Map)
.values()
)
.flat();
console.log(array);
我有这样的数组:
Arr = [{name:"abc",age:1},{name:"a",age:4},{name:"ac",age:3},{name:"abc",age:2},{name:"abc",age:9}]
我想这样改:
[{name:"abc",age:1},{name:"abc",age:2},{name:"abc",age:9},{name:"a",age:4},{name:"ac",age:3}]
通过排序或交换。
试试这个
arr1.sort((a, b) => {
if(a.name.startsWith(b.name)) { return -1; }
if(a.name < b.name) { return -1; }
if(a.name > b.name) { return 1; }
return 0;
})
您可以使用 Map
收集相同命名的对象并取回扁平值。
此方法保持 name
的给定顺序并将该对象同名组合在一起。
var array = [{ name: "abc", age: 1 }, { name: "a", age: 4 }, { name: "ac", age: 3 }, { name: "abc", age: 2 }, { name: "abc", age: 9 }];
array = Array
.from(array
.reduce((m, o) => m.set(o.name, [...(m.get(o.name) || []), o]), new Map)
.values()
)
.flat();
console.log(array);