I have an array of object, this array contains differents names.
[ "Foo", "Bar", "Test", "Other" ];
And another array of object
[ { name:"Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 } ]
I need to create an array of them, the new array contains sub array with a size of 2, first index the name and second index the value. The order of the array need to be the same of the first one (array of names).
Like
[ ["Foo", 120], ["Bar", 159], ["Test", undefined], ["Other", 1230] ]
So I try this code, but my output is not correct. The order of name is correct but the order of value is not.
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var array = order.map(function(name, i) {
return [name, (values[i] && values[i].value) ];
})
console.log(array)
You could take a Map and get the items in the wanted order.
var names = [ "Foo", "Bar", "Test", "Other" ],
objects = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }],
map = new Map(objects.map(({ name, value }) => [name, value])),
result = names.map(name => [name, map.get(name)])
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You're nearly there - you just need to find the correct value:
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var array = order.map(function(name, i) {
return [name, values.some(e => e.name == name) ? values.find(e => e.name == name).value : undefined];
})
console.log(array)
ES5 syntax:
var order = ["Foo", "Bar", "Test", "Other"];
var values = [{ name: "Bar", value: 159 }, { name: "Foo", value: 120 }, { name: "Other", value: 1230 }];
var array = order.map(function(name, i) {
return [name, values.some(function(e) {
return e.name == name;
}) ? values.find(function(e) {
return e.name == name;
}).value : undefined];
});
console.log(array)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With