javascript - How to sort an array of objects in the order of another array containing the unique values of a property present in each object? -
i have have 2 arrays, want merge them 1 object. have given examples of have , want achieve. tried _.union
, few other underscore methods.
var original = [ { country: 'us', value: '10' }, { country: 'turkey', value: '5' } ]; var newlist =["afghanistan", "antarctica","turkey"]
the results want:
var results= [ { country: 'afghanistan', value: '0' }, { country: 'antarctica', value: '0' }, { country: 'turkey', value: '5' } ];
the not appear in final results because newlist doesn't have us. values new list appear in results values original list.
a non-underscore solution, .map()
s new array, returning object original array if can .find()
it, otherwise returning new object:
var original = [ { country: 'us', value: '10' }, { country: 'turkey', value: '5' } ]; var newlist =["afghanistan", "antarctica","turkey"] var result = newlist.map(function(v) { return original.find(function(o) { return o.country === v }) || { country: v, value: '0' } }) console.log(result)
it's one-liner es6 arrow functions:
var original = [ { country: 'us', value: '10' }, { country: 'turkey', value: '5' } ]; var newlist =["afghanistan", "antarctica","turkey"] var result = newlist.map(v => original.find(o => o.country===v) || {country:v, value:'0'}) console.log(result)
Comments
Post a Comment