0

I have a array of ibject with another object inside each element like

data = [
  {
    name: "A",
    type: "AA",
    children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [ { id: 2, name: "Child-B" }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [ { id: 3, name: "Child-C" }],
    other: "NA"
  }

] 

I want to order the whole collection by the children.id value but based on the order given by another array

orderArray = [3, 1, 2] 

So the output would be

data =[
    {
        name: "C",
        type: "CC",
        children: [ { id: 3, name: "Child-C" }],
        other: "NA"
    },
    {
        name: "A",
        type: "AA",
        children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
        other: "NA"
    },
    {
        name: "B",
        type: "BB",
        children: [ { id: 2, name: "Child-B" }],
        other: "NA"
    }
]
Hector Landete
  • 357
  • 1
  • 6
  • 15

2 Answers2

0

You can pass a comparator to Array.sort which compares/sorts by index of children[0].id in orderArray array

let data = [{name:"A",type:"AA",children:[{id:1,name:"Child-A",admin:["Y"]}],other:"NA"},{name:"B",type:"BB",children:[{id:2,name:"Child-B"}],other:"NA"},{name:"C",type:"CC",children:[{id:3,name:"Child-C"}],other:"NA"}];
let orderArray = [3, 1, 2];

data.sort((a,b) => orderArray.indexOf(a.children[0].id) - orderArray.indexOf(b.children[0].id));
console.log(data);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

Try this:

var newdataArray = []

orderArray.forEach(index => {
    newdataArray.push(data[index - 1])
});

data = newdataArray
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79