Combining elements of 2 dimentional array

335
November 23, 2016, at 1:44 PM

I have an JavaScript array:

var arr = [["A",["05",90]],["A",["04",240]],["A",["03",235]],["B",["00",123]],["B",["01",234]]];

I want final array to look like:

var final = [["A",[["05",90],["04",240],["03",235]]],["B",[["00",123],["01",234]]]];

The final array is formed by combining all the 2nd element of 2 dimensional array when the 1st element matches. Please advice how can this be achieved in JavaScript

Answer 1

Object keys are generally the easiest way to create groups like this

var tmp = {}; // temporary grouping object
// loop over data
arr.forEach(function (item) {
    // check if group started
    if (!tmp.hasOwnProperty(item[0])) {
        tmp[item[0]] = [];
    }
    // push data to group
    tmp[item[0]].push(item[1]);
});
// map temp object to results array
var results = Object.keys(tmp).map(function (key) {
    return [key, tmp[key]];
});

DEMO

Answer 2

If you start with the array you gave:

var arr = [["A",["05",90]],["A",["04",240]],["A",["03",235]],["B",["00",123]],["B",["01",234]]];

then create a new array to store the values:

var final = [];

and simply combine all of the third-level elements (such as ["05",90] and ["01",234]) of each second-level ones (such as "A" and "B") by looping through the array:

for(var i = 0; i < arr.length; i++) {
    var found = false;
    for(var j = 0; j < final.length; j++) {
        if(arr[i][0] == final[j][0]) {
            final[j][1].push(arr[i][1]);
            found = true;
            break;
        }
    }
    if(!found) {
        final[final.length] = [arr[i][0], [[arr[i][1][0], arr[i][1][1]]]];
    }
}

This is essentially a sorting method: if the "key" is equal to one in the final array, then it adds it to that one. If not, then appends it to the end of final.

Here's the working example on JSFiddle: link.

This outputs the array:

["A", [["05", 90], ["04", 240], ["03", 235]]], ["B", [["00", 123], ["01", 234]]]

as requested.

Also, as @PaulS commented, it would be recommended to use Objects instead as Strings, to make them Key-Value pairs. But in my answer I stuck with arrays.

Rent Charter Buses Company
READ ALSO
Google Maps - Dynamically Generating Markers on Map [closed]

Google Maps - Dynamically Generating Markers on Map [closed]

I"m new to google maps and am trying to get all the locations that are returned on my search page to appears on the corresponding map but I can't make it work. I have each listing display their longitude and latitude with the listing and I'm using the code below....

293
Using jQuery to toggle menu visibility

Using jQuery to toggle menu visibility

I have a code for a navigation page I'm working on, to be used on the tumblr platform. The navigation is basically set up like so, with #navstart being the category of the navigation items and #navitem used for individual items.

398
Can the JS Prepend statement edit pre-defined html?

Can the JS Prepend statement edit pre-defined html?

I define my html by setting it equal to a variable i am echoing, just for the sake of keeping my php page dynamic, however i am trying to append another input div onto my text area once a button is clicked via a javascript statement. In terms of syntax...

320
execute input jquery event only when there&#39;s a pause

execute input jquery event only when there's a pause

I have a search input box on a simple form that automatically fetches remote data based on what's entered. A minimum 3 characters is needed to trigger the search.

334