Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array based on two array

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)
like image 599
Kamoulox Avatar asked Mar 04 '26 19:03

Kamoulox


2 Answers

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; }
like image 88
Nina Scholz Avatar answered Mar 06 '26 10:03

Nina Scholz


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)
like image 32
Jack Bashford Avatar answered Mar 06 '26 10:03

Jack Bashford