Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
How to group two-dimensional array by value at zero index

Let's say I have the following two-dimensional array:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];

What I want to do is to find all the values under first index which have common zero index value. So the result should be the following:

[[1, [1, 2]], [2, [1, 2]]]

Or maybe Map would look better:

[Map(1 => [1, 2]), Map(2 => [1, 2])]

How can I do that? With or without lodash. My solution looks a bit bloated and messy:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouppedCartItemsMap = new Map();

array.forEach((item) => {
  const [locationId, contractId] = item;

  if (!grouppedCartItemsMap.has(locationId)) {
    grouppedCartItemsMap.set(locationId, [contractId]);
  } else {
    const existingItem = grouppedCartItemsMap.get(locationId);

    if (!existingItem.includes(contractId)) {
      grouppedCartItemsMap.set(locationId, [...existingItem, contractId]);
    }
  }
});
console.log(grouppedCartItemsMap);

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If an object would work:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouped = {};
for (const [first, last] of array) {
  grouped[first] ??= [];
  grouped[first].push(last);
}
console.log(grouped);

about 4 years ago · Juan Pablo Isaza Report

0

This looks like a use case for reduce:

const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouppedCartItemsMap = array.reduce((acc, [locationId, contractId]) => {
  if (!acc.has(locationId)) acc.set(locationId, [contractId]);
  else acc.get(locationId).push(contractId);
  return acc;
}, new Map());
console.log([...grouppedCartItemsMap.entries()]);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!