1
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'}
]

2 Answers 2

6

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)

Sign up to request clarification or add additional context in comments.

1 Comment

It might be worth it to use some variety of "map" to make the lookup of the key indexes faster. The example given to us is very simple, but if he should get back quite a few rows then the constant indexOf calls could get expensive.
2

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);

6 Comments

This is close, but it doesn't preserve the order of the keys missing keys.
@danh Yes it does. If both A and B don't exist in the array, then B will be put second. Admittedly, it does depend on which sort the browser implements.
@danh Slightly better time complexity than your answer as well :P
Please review the output of your code for "g" and "b". Time complexity of both solutions is O(n log n)
incorrect order of "b","g", swap you condition statements and it will be the correct "g","b"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.