search

Home  >  Q&A  >  body text

sort - javascript manually specify the order of an array of objects

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' } ]
淡淡烟草味淡淡烟草味2774 days ago716

reply all(2)I'll reply

  • 黄舟

    黄舟2017-06-28 09:29:54

    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

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-28 09:29:54

    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

    reply
    0
  • Cancelreply