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"
    }
]
0

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

var newdataArray = []

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

data = newdataArray

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.