0

I have an array of objects and I have array of numbers and I want objects to be arranged as per numbers in array. Using lodash sortby I tried to get desired result but that didn't work.

Here is what I tried

import * as _ from 'lodash';

let keys = [ '10001', '10002', '10004' ];
let c = [
  {
    name: 'John',
    id: 10004,
  },
  {
    name: 'Alice',
    id: 10001,
  },
  {
    name: 'Bob',
    id: 10002,
    is_app: 1,
  },
]

const result = _.sortBy(c,keys);
// this is still printing original array

This is what I expect it to print

[
  {  
    name: 'Alice',
    id: 10001,
  },
  {  
    name: 'Bob',
    id: 10002,
  },
  {  
    name: 'John',
    id: 10004,
  }
]

Any help or suggestion how to do this will be of great help:)

karPower
  • 15
  • 3
  • Does this answer your question? [Sorting an array in Javascript based on predefined order](https://stackoverflow.com/questions/33472458/sorting-an-array-in-javascript-based-on-predefined-order) – InSync Apr 17 '23 at 16:32
  • Thanks for suggestion , tried implement it but keys.indexOf(a.id) it needs a string but I have array of numbers – karPower Apr 17 '23 at 16:42
  • Then simply convert it into a number (or vice versa). – InSync Apr 17 '23 at 16:43
  • Thanks converting toString that works. – karPower Apr 17 '23 at 16:49
  • You don't have an array of numbers, you have an array of strings. The question is, why do you have the array of strings when it appears to be stringified duplicate information from the objects? A lot of the design of this approach seems arbitrary. – Abion47 Apr 17 '23 at 16:50

0 Answers0