I have an object array. I want it to be arranged in the order I specified. As follows, it is arranged in the order of the names I specified. I will use the following method to do it with pure native JavaScript. Is there any lodash or Can other well-known third-party packages achieve the following effects, or are there other more efficient and simple ways to write them?
var arr = [
{
name:'小麦',
phone:'112233'
},
{
name:'绿绿',
phone:'4445566'
},
{
name:'增增',
phone:'321321'
},
{
name:'弱弱',
phone:'123123'
}
];
//希望达到的顺序 (我已知所有元素)
var order = {
'增增':0,
'弱弱':1,
'绿绿':2,
'小麦':3
};
var newOrderedArr = [];
arr.forEach((element)=>{
newOrderedArr[order[element.name]] = element;
});
console.log(newOrderedArr);
The results of console are as follows
[ { name: '增增', phone: '321321' },
{ name: '弱弱', phone: '123123' },
{ name: '绿绿', phone: '4445566' },
{ name: '小麦', phone: '112233' } ]
If
orders
contains continuous values from0 ~ n
, then your method is already very, very fast, and other library methods cannot reach this speed (because they will consider discontinuous situations)If they are not continuous, you can use sort
Or you can use your method and add a filter
Supplement: For the case of non-consecutive serial numbers, the comparison without sorting is as shown in the figure
This idea seems to be very fast. From the perspective of ease of use, the index of order can be generated so that an array of names can be entered each time.
But not if there are duplicate names. You have to maintain an array record for each name and finally concat it