Perform Lookup On Two Arrays And Add Element From Second Array To First Array
I have two arrays that I have looped over to match an element from the 1st array vals1 in the second onevals2. If the element(index [i][0]) from vals1 is present in vals2(index [j]
Solution 1:
- Iterate through all items in the first 2D array (
vals1
). You can do that with forEach, for example. - For each item in
vals1
, you want to look for the same item invals2
. You can use find for that. Since items are the first element in each inner array, you would have to check whetheritem1[0] === item2[0]
. - If the item is found, push the corresponding value
item2[1]
to the item's inner array invals1
. - If the item is not found (
find
returnsundefined
), push the string"Unassigned"
instead.
Code snippet:
functionlookup(vals1, vals2) {
vals1.forEach(item1 => {
const item2 = vals2.find(item2 => item1[0] === item2[0]);
const newValue = item2 ? item2[1] : "Unassigned";
item1.push(newValue);
});
return vals1;
}
Regular function syntax:
functionlookup(vals1, vals2) {
vals1.forEach(function(item1) {
const item2 = vals2.find(function(item2) {
return item1[0] === item2[0]
});
const newValue = item2 ? item2[1] : "Unassigned";
item1.push(newValue);
});
return vals1;
}
Solution 2:
Try this:
functionmyFunc() {
let v1 = [[ 'item3', 3, 2, 6 ],[ 'item6', 4, 7, 28 ],[ 'item8', 1, 8, 8 ],[ 'item2', 6, 12, 72 ]];
let v2 = [[ 'item1', 15 ],[ 'item2', 4 ],[ 'item3', 1 ],[ 'item4', 2 ]];
let v0 =v2.map(r=>{return r[0]});//just getting all of the the first elements of v2 in a flatten array for use with indexOf
v1.forEach((r,i)=>{
let idx=v0.indexOf(r[0]);
if(idx>-1) {//if idx is greater than -1 the matches first element v2
v1[i].push(v2[idx][1]);
}else{
v1[i].push('UnAssigned')
}
});
console.log(v1);
}
The output was:
[ [ 'item3', 3, 2, 6, 1 ],
[ 'item6', 4, 7, 28, 'UnAssigned' ],
[ 'item8', 1, 8, 8, 'UnAssigned' ],
[ 'item2', 6, 12, 72, 4 ] ]
Post a Comment for "Perform Lookup On Two Arrays And Add Element From Second Array To First Array"