Badrush
Badrush

Reputation: 1287

Combining 2D Array with Key-Value Array

I have an array where each row is an array that has 2 values, S/N and Description.

 array1 = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];

As you can see there are duplicates. So I wrote code that creates a count array that holds the key-value pairs and counts each item. Length of count is 1.

count = [xx1: 1
         xx9: 3] 

So now I want to combine the two arrays into one new one that includes the quantity, in this example the final output would be as shown below. Note that I have to also remove the duplicates in array1. Order doesn't matter.

 final_array = [["1","xx1","Small Car"],["3",xx9","Big Car"]];

Here is my JS code so far but basically the .forEach loops won't work over the count array. Can anyone help me so that this code works on the key-value array.

JS/Jquery:

//Pull the Cart Data & Orangize
var savedList = JSON.parse(localStorage.getItem("partList"));
        console.log(savedList);
        determineQuantity(savedList); //Count quantity of each item

//Count the Quantity of each item in saved list & create key-value pairs
function determineQuantity(savedList){
    var newList = [];
    var count = [];
    for (var i=0, j = savedList.length; i<j; i++){
        count[savedList[i][0]] = (count[savedList[i][0]] || 0) + 1;
    };
        console.log(count);
    //Combine Quantity Array with SavedList Array
    count.forEach(function(item,index){ 
                    console.log("index = " + index + "  item = " + item);
          savedList.forEach(function(row){
                if ($.inArray(item,row == 0)){ //if found in this row at index 0
                     var new_part = [count[index],row[0],row[1]];
                            console.log("new_part = " + new_part);
                     newList.push(new_part);
                };  
        });
    });
    console.log(newList);
};

Upvotes: 0

Views: 81

Answers (1)

subash
subash

Reputation: 3140

how about this.

var test = function(){
    var array = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];
    var count = {xx1: 1, xx9: 3};
    var map = {};
    array.forEach(function(item){map[item[0]] = item[1]});
    var newArray = [];
    for(var key in count){
        if(!map[key])
            continue;
        newArray.push([count[key], key, map[key]]);
    }
    console.log(newArray);
}

first of all, you count is a object, not a array. then we dont need forEach

Upvotes: 1

Related Questions