skip to Main Content

I’ve an array with arrays of different values that I need to re arrange.

Original Array

$cars = [
  [2022, "Corolla"],
  [2022, "Toyota"],
  [2021, "Corolla"],
  [2021, "Toyota"],
  [2021, "Honda"]
];

Expected Array

$resultCars = [
  [2022, "Corolla", "Toyota"],
  [2021, "Corolla", "Toyota", "Honda"]
];

4

Answers


  1. Here’s how I would do it in Javascript:

    ResultCars = Cars.reduce((carry, [year, make]) =>
    {
        let item = carry.find(([existingYear]) => existingYear === year);
        if(item)
            item.push(make);
        else
            carry.push([year, make]);
    
        return(carry);
    }, []);
    
    Login or Signup to reply.
  2. const cars = [
      [2022, "Corolla"],
      [2022, "Toyota"],
      [2021, "Corolla"],
      [2021, "Toyota"],
      [2021, "Honda"]
    ];
    console.log(Object.entries(cars.reduce((a,[year,make])=>
      ((a[year]??=[]).push(make), a), {})).map(i=>i.flat()))
    Login or Signup to reply.
  3. Here is an approach in C++:

    vector<pair<int, string>> cars {
        {2022, "Corolla"},
        {2022, "Toyota"},
        {2021, "Corolla"},
        {2021, "Toyota"},
        {2021, "Honda"}
    };
    
    map<int, set<string>> resultCars;
    for (const auto& c : cars)
    {
        resultCars[c.first].insert(c.second);
    }
    

    As a full example (live demo):

    #include <iostream>
    #include <iterator>
    #include <map>
    #include <set>
    #include <string>
    #include <utility>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        // Input
        vector<pair<int, string>> cars {
            {2022, "Corolla"},
            {2022, "Toyota"},
            {2021, "Corolla"},
            {2021, "Toyota"},
            {2021, "Honda"}
        };
    
        // Index
        map<int, set<string>> resultCars;
        for (const auto& c : cars)
        {
            resultCars[c.first].insert(c.second);
        }
    
        // Output
        for (const auto& c : resultCars)
        {
            int year = c.first;
            const auto& names = c.second;
            cout << year << " : ";
            copy(names.begin(), names.end(), ostream_iterator<string>(cout, " "));
            cout << "n";
        }
    }
    
    Login or Signup to reply.
  4. In JS:

    const Cars = [ [2022, "Corolla"], [2022, "Toyota"], [2021, "Corolla"], [2021, "Toyota"], [2021, "Honda"] ];
    
    const res = Cars.reduce((a, [year, name]) => ((a[year] ??= [year]).push(name),a),{});
    
    console.log(Object.values(res));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search