Reputation: 5271
I am trying to achieve that, fruits is checked in onTruck to find the existing keys, then push to a new array. Since they are different length, I am stuck on how to loop them.
var fruits = ['apple', 'orange', 'banana']
var onTruck = {
'apple': 100,
'orange': 200,
'banana': 500,
'pineapple': 5,
'mango': 'empty'
}
let arr = []
Object.keys(onTruck).forEach((e, i) => {
console.log(e === fruit[]) <- Need to loop fruit
arr.push[...]
})
// OUTPUT:
arr = [['apple', '100'],['orange', '200'], ['banana', '500'] ]
Upvotes: 3
Views: 103
Reputation: 115222
Use Array#map
method to generate a new array based on the key element array.
var fruits = ['apple', 'orange', 'banana']
var onTruck = {
'apple': 100,
'orange': 200,
'banana': 500,
'pineapple': 5,
'mango': 'empty'
}
var arr = fruits.map(v => [v, onTruck[v]]);
// in case some fields may miss in onTruck then add an additional filter
var arr1 = fruits.filter(v => v in onTruck).map(v => [v, onTruck[v]]);
// or with reduce
var arr2 = fruits.reduce((a, v) => v in onTruck ? [...a, [v, onTruck[v]]] : a, []);
console.log(arr)
console.log(arr1)
console.log(arr2)
FYI : If you want to ignore properties which is not number or value is empty
then use an additional filter condition(or filter).
For avoiding non digit values : !isNaN(onTruck[v])
For avoiding property with value 'empty'
: onTruck[v] !== 'empty'
For eg:
var arr = fruits.filter(v => v in onTruck && !isNaN(onTruck[v])).map(v => [v, onTruck[v]]);
Upvotes: 3
Reputation: 2134
var fruits = ['apple', 'orange', 'banana']
var onTruck = {
'apple': 100,
'orange': 200,
'banana': 500,
'pineapple': 5,
'mango': 'empty'
}
let arr = fruits.reduce((arr,b) => {
if (!isNaN(onTruck[b])){
arr.push([b, onTruck[b]]);
return arr;
} else return arr;
},[])
console.log(arr)
Upvotes: 0
Reputation: 2228
var newArray = fruits.filter(function(fruit) {
return fruit in onTruck;
}).map(function(fruit) {
return [fruit, onTruck[fruit]]
});
Should work. Basically, I am filtering fruits existing in onTruck
and then constructing the required array through the map function.
Upvotes: 0
Reputation: 16908
You can simplify the code by using Array.filter
and Array.map
:
var fruits = ['apple', 'orange', 'banana'];
var onTruck = {
'apple': 100,
'orange': 200,
'banana': 500,
'pineapple': 5,
'mango': 'empty'
}
const result = Object.keys(onTruck)
.filter((fruit) => fruits.includes(fruit))
.map((fruit) => [fruit, onTruck[fruit]]);
console.log(result);
Upvotes: 1