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

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -