3

Gived a list

[
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'},
]

and another ordered id list

['i1','i2','i3','i4','i5']

get

[
{id:'i1',value:'v1'},
{id:'i2',value:'v2'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i5',value:'v5'},
]

How to do this in lodash?

2
  • will these lists have always the same elements or could it be that they are 'off' on certain elements? Commented Sep 17, 2018 at 7:04
  • @Falk The lists may have any elements with a random id. Actually the data list is queried by id list from server. But the server can't promise the order of data will not be changed so I need to sort the data manually. Commented Sep 17, 2018 at 7:15

4 Answers 4

2

Use sortBy method and return the id's index position from the iteratee function

let sortedArray = _.sortBy(input, (v) => order.indexOf(v.id))

where

input = [
  {id:'i1',value:'v1'},
  {id:'i3',value:'v3'},
  {id:'i4',value:'v4'},
  {id:'i2',value:'v2'},
  {id:'i5',value:'v5'},
]
order = ['i1','i2','i3','i4','i5']
Sign up to request clarification or add additional context in comments.

2 Comments

I think this is a better answer. Thank everyone.
It is worth mentioning that (v) => order.indexOf (v.id) is called N times, and order.indexOf has complexity O(N).
0

Convert Array to Object where key is id for better lookup. Replace each element in ordered list with actual value.

Edge case: the two array has the same elements

const foo = [
  {id:'i1',value:'v1'},
  {id:'i3',value:'v3'},
  {id:'i4',value:'v4'},
  {id:'i2',value:'v2'},
  {id:'i5',value:'v5'},
];

const ordered = ['i1','i2','i3','i4','i5'];

const fooMap = _.keyBy(f, 'id');

const orderedFoo = ordered.map(id => fooMap[id])

Comments

0
const arr = ['i1','i2','i3','i4','i5'];
const arrObj = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'}
]
const sortedArr = [];

_.map(arr, a => sortedArr.push(_.find(arrObj, ['id', a])));
console.log(sortedArr)

Comments

0
let arr = ['i1','i2','i3','i4','i5'];
let arrObj = [
    {id:'i1',value:'v1'},   
    {id:'i3',value:'v3'},
    {id:'i4',value:'v4'},
    {id:'i2',value:'v2'},
    {id:'i5',value:'v5'}
]

console.table(arrObj);

arr.map(v => {
    arrObj.sort( v1 => { return v1.id == v ? true : false} )
})

console.table(arrObj);

Comments

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.