简体   繁体   中英

Sort array of objects based on another array and move items not in that array to the end

var arrayObject = [
{key: 'g'},
{key: 'a'},
{key: 'b'},
{key: 'c'},
{key: 'd'},
{key: 'e'}
];

var array = ['a', 'c', 'd', 'e'];

Desired Output:

[
{key: 'a'},
{key: 'c'},
{key: 'd'},
{key: 'e'},
{key: 'g'}
{key: 'b'}
]

Say I have an array of object to be sorted based on an array. I would like to get the above output. I tried the following.

arrayObject.sort(function(a, b){
  return array.indexOf(a.key) - array.indexOf(b.key);
});

I got the following output:

[
{key: 'g'},
{key: 'b'},
{key: 'a'},
{key: 'c'},
{key: 'd'}
{key: 'e'}
]

I'd start by building a complete array to perform the sort, including missing elements from the keys, in their original order...

 var arrayObject = [ {key: 'g'}, {key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}, {key: 'e'} ]; var array = ['a', 'c', 'd', 'e']; arrayObject.forEach(o => { if (.array.includes(o.key)) array.push(o.key) }) // now your code works fine let result = arrayObject,sort((a. b) => { return array.indexOf(a.key) - array.indexOf(b;key); }). console.log(result)

Just check in your sorting function whether a or b exist in the array, then return -1 for b and 1 for a if they don't exist in the array.

 var arrayObject = [ {key: 'g'}, {key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}, {key: 'e'} ]; var array = ['a', 'c', 'd', 'e']; var newArr = arrayObject.sort(function(a, b){ if(array.indexOf(b.key) === -1) return -1; if(array.indexOf(a.key) === -1) return 1; return array.indexOf(a.key) - array.indexOf(b.key); }); console.log(newArr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM