skip to Main Content

i have a question with javascript.
I have a array data like this:

myArray = [
  { productId: 1, tableId: 1 },
  { productId: 1, tableId: 2 },
  { productId: 2, tableId: 1 },
  { productId: 2, tableId: 2 },
  { productId: 2, tableId: 3 },
  { productId: 2, tableId: 4 },
  { productId: 3, tableId: 1 },
  { productId: 4, tableId: 1 },
];

I want to convert this into:

result = [
    {
        productIds: [1, 2],
        tableIds: [1, 2],
    },
    {
        productIds: [2],
        tableIds: [3, 4],
    },
     {
        productIds: [3, 4],
        tableIds: [1],
    }
]

How do I handle this? Thanks for your help.

2

Answers


  1. let myArray = [{
        productId: 1,
        tableId: 1
      },
      {
        productId: 1,
        tableId: 2
      },
      {
        productId: 2,
        tableId: 1
      },
      {
        productId: 2,
        tableId: 2
      },
      {
        productId: 2,
        tableId: 3
      },
      {
        productId: 2,
        tableId: 4
      },
      {
        productId: 3,
        tableId: 1
      },
      {
        productId: 4,
        tableId: 1
      },
    ];
    
    function groupConvertor(myArray) {
      let obj = {};
      myArray.forEach((e, i) => {
        if (obj[e.productId]) {
          obj[e.productId] = [...obj[e.productId], ...[e.tableId]];
        } else {
          obj[e.productId] = [e.tableId]
        }
      });
      let arr = [];
      for (let x in obj) {
        let obj1 = {
          productIds: [Number(x)],
          tableIds: obj[x]
        }
        arr.push(obj1);
      }
      return arr;
    }
    console.log(groupConvertor(myArray));
    Login or Signup to reply.
  2. The sort() method for arrays can take in custom function for sorting an array. Here’s what the MSDN documentation says about it:

    A function that defines the sort order. The return value should be a number whose sign indicates the relative order of the two elements: negative if a is less than b, positive if a is greater than b, and zero if they are equal. NaN is treated as 0. The function is called with the following arguments:

    a
    The first element for comparison. Will never be undefined.

    b
    The second element for comparison. Will never be undefined.

    Here’s an example of it, using the array from your code:

    let result = myArray.sort((a, b) => {
        if (a.tableId < b.tableId)
            return -1;
        else if (a.tableId > b.tableId)
            return 1;
        else
            return 0;
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search