Reputation: 33
I have two formatted array as below code, and I would like to match the id and get the matched id value of size and stock
I have the code from github as below but can not get it to work
var arraysize = [];
var arraycode = [];
var code = '{id:'+stock[i][1] +',stock:'+ stock[i][4]+'}';
var size = '{id:'+tomatchcode+',size:'+tomatchsize+'}';
arraycode[i] = code;
arraysize[i] = size;
Logger.log(arraysize);
Logger.log(arraycode);
[19-08-29 10:32:35:003 ICT] [{id:59,size:36}, {id:123,size:37}, {id:62,size:38}, {id:63,size:39}, {id:64,size:40}]
[19-08-29 10:32:35:003 ICT] [{id:63,stock:17}, {id:123,stock:16}, {id:59,stock:10}, {id:64,stock:12}, {id:62,stock:14}]
//both array id value in random position but have same value
var matcharray =checkArrayForMatches(arraycode,arraysize)
function checkArrayForMatches(array,properties){
var returnArray = [];
if (Array.isArray(array[0])){
for (var i = 0,x = array.length;i<x;i++){
var row = array[i];
var match = true;
for (var j in properties){
if (properties[j] !== row[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
} else if (typeof array[0] == 'object'){
for (var i = 0,x = array.length;i<x;i++){
var obj = array[i];
var match = true;
for (var j in properties){
if (obj[j] !== properties[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
}
return returnArray;
}
The above function not returning any value. I would like it to returning array like this which contain size value following by stock value [{36,10}, {37,16}, {38,13}, {39,17}, {40,12}] As you can see each returned value have a matching id.
Any help is much appreciated.
Upvotes: 1
Views: 493
Reputation: 50462
id:stock
Array.map
to retrieve stock
from hash table using id
of arraysize
var arraysize = [{ id: 59, size: 36}, { id: 123, size: 37}, { id: 62, size: 38}, { id: 63, size: 39}, { id: 64, size: 40}];
var arraycode = [{ id: 63, stock: 17}, { id: 123, stock: 16}, { id: 59, stock: 10}, { id: 64, stock: 12}, { id: 62, stock: 13}];
var arrayCodeObj = {};
arraycode.forEach(function(obj){arrayCodeObj[obj.id]=obj.stock});//create hash table
var arr2d = arraysize.map(function(obj){ return [obj.size, arrayCodeObj[obj.id]]})
console.log(arr2d)
console.log(arrayCodeObj)
Upvotes: 4