I have 2 arrays as follows.
Array 1
let array1 = [ { name:1, options: {layer:mynode:Cat} }, { name:randomName, options: {layer:mynode:Dog} }, { name:randomName2, options: {layer:mynode:Lion} } ]
And the next array
Array 2
let array2 = ["Dog","Lion","Cat"]
I want to sort the array1 according to the data order in array2. I have tried something like this but it’s giving me a undefined result
sortedArr = array2.map((object,key) => array1[((options.layers).split(':'))[1]]);
Can someone help me with this?
Advertisement
Answer
let array1 = [ { name: 1, options: { layer: "mynode:Cat" }, }, { name: 2, options: { layer: "mynode:Dog" }, }, { name: 3, options: { layer: "mynode:Lion" }, }, ]; let array2 = ["Dog", "Lion", "Cat"]; array1.sort((a, b) => { return array2.indexOf(a.options.layer.split(":")[1]) > array2.indexOf(b.options.layer.split(":")[1]) ? 1 : -1; }); console.log(array1);