Created
July 17, 2017 19:02
-
-
Save anonymous/9a48c137344ba61b6d31095d742e53aa to your computer and use it in GitHub Desktop.
Merge Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js" type="text/javascript" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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