Home > Enterprise >  How to change index of elements in array of objects according to another array JavaScript?
How to change index of elements in array of objects according to another array JavaScript?

Time:12-27

I have two arrays and need to change the order of elements in a way to be similar. by property c. i should get index of object of property c: 2 for example and place it to the right index in arrB . JavaScript

const arrA= [{
    a: 1,
    b: [{
        c: 2,
        d: 3
      },
      {
        c: 5,
        f: 6
      }
    ]
  },
  {
    a: 2,
    b: [{
        c: 2,
        d: 3
      },
      {
        c: 5,
        f: 6
      }
    ]
  }
];

const arrB = [{
    a: 1,
    b: [{
        c: 5,
        f: 6
      },
      {
        c: 2,
        d: 3
      },
    ]
  },
  {
    a: 2,
    b: [{
        c: 5,
        f: 6
      },
      {
        c: 2,
        d: 3
      },
    ]
  }
];

What I need is to sort arrB in order of all elements in key b to have the same order like in arrA. in reality this object contain more fields and they aren't similar. but they have the same property c by which i should change the order

const arrB= [{
    a: 1,
    b: [{
        c: 2,
        d: 3
      },
      {
        c: 5,
        f: 6
      }
    ]
  },
  {
    a: 2,
    b: [{
        c: 2,
        d: 3
      },
      {
        c: 5,
        f: 6
      }
    ]
  }
];

CodePudding user response:

You can use sort() to order the elements based on the indexes of the matching elements in arrA[i].b.

const arrA = [{
    a: 1,
    b: [{
        c: 2,
        d: 3
      },
      {
        c: 5,
        f: 6
      }
    ]
  },
  {
    a: 2,
    b: [{
        c: 2,
        d: 3
      },
      {
        c: 5,
        f: 6
      }
    ]
  }
];

const arrB = [{
    a: 1,
    b: [{
        c: 5,
        f: 6
      },
      {
        c: 2,
        d: 3
      },
    ]
  },
  {
    a: 2,
    b: [{
        c: 5,
        f: 6
      },
      {
        c: 2,
        d: 3
      },
    ]
  }
];

arrB.forEach((item, i) =>
  item.b.sort((el1, el2) => arrA[i].b.findIndex(el => el.c == el1.c) - arrA[i].b.findIndex(el => el.c == el2.c)));

console.log(arrB);

  • Related