Use array as sort order in JavaScript


const sort = ["this","is","my","custom","order"];
const myObjects = [
   {"id":1,"content":"is"},
   {"id":2,"content":"my"},
   {"id":3,"content":"this"},
   {"id":4,"content":"custom"},
   {"id":5,"content":"order"}
];

We are required to write a JavaScript function that takes in two such arrays and sorts the second array of objects on the basis of the first array so that the content property of objects are matched with the strings of the first array.

Therefore, for the above arrays the output should look like −

const output = [
   {"id":3,"content":"this"},
   {"id":1,"content":"is"},
   {"id":2,"content":"my"},
   {"id":4,"content":"custom"},
   {"id":5,"content":"order"}
];

Example

The code for this will be −

const arrLiteral = ["this","is","my","custom","order"];
const arrObj = [
   {"id":1,"content":"is"},
   {"id":2,"content":"my"},
   {"id":3,"content":"this"},
   {"id":4,"content":"custom"},
   {"id":5,"content":"order"}
];
const sortByReference = (arrLiteral, arrObj) => {
   const sorted = arrLiteral.map(el => {
      for(let i = 0; i < arrObj.length; ++i){
         if(arrObj[i].content === el){
            return arrObj[i];
         }
      };
   });
   return sorted;
};
console.log(sortByReference(arrLiteral, arrObj));

Output

And the output in the console will be −

[
   { id: 3, content: 'this' },
   { id: 1, content: 'is' },
   { id: 2, content: 'my' },
   { id: 4, content: 'custom' },
   { id: 5, content: 'order' }
]

Updated on: 20-Nov-2020

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements