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

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