Skip to content

Instantly share code, notes, and snippets.

@rjchicago
Forked from anonymous/index.html
Created July 17, 2017 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjchicago/d54604736809a1f6a7f0afb64af78906 to your computer and use it in GitHub Desktop.
Save rjchicago/d54604736809a1f6a7f0afb64af78906 to your computer and use it in GitHub Desktop.
Merge Lists
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js" type="text/javascript" />
const merge = (lists, key) => {
const o = {};
_.each(lists, (list) => {
_.each(list, (item) => {
// order of the lists matters, preserve prior values and do not overwrite...
if (typeof item[key] !== 'undefined' && typeof o[item[key]] === 'undefined') {
o[item[key]] = item;
}
});
});
return _.map(o, (value, key) => { return value; });
};
const lists = [
[{key:0, value:'list0 key0'},{key:1, value:'list0 key1'},{key:2, value:'list0 key2'}],
[{key:0, value:'list1 key0'},{key:10, value:'list1 key10'},{key:20, value:'list1 key20'}],
[{key:0, value:'list2 key0'},{key:10, value:'list2 key10'},{key:200, value:'list2 key200'}],
];
const list = merge(lists, 'key');
console.log(JSON.stringify(list));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment