亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

sort - javascript manually specify the order of an array of objects
淡淡煙草味
淡淡煙草味 2017-06-28 09:27:54
0
2
766

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' } ]
淡淡煙草味
淡淡煙草味

reply all(2)
黃舟

If orders contains continuous values ??from 0 ~ 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

newOrderedArr = arr.sort((a, b) => order[a.name] - order[b.name]);

Or you can use your method and add a filter

newOrderedArr = newOrderedArr.filter(n => n);

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template