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
The
sort()
method for arrays can take in custom function for sorting an array. Here’s what the MSDN documentation says about it:Here’s an example of it, using the array from your code: