Как конкатенировать два массива объектов без дублей?
Есть два массива объектов:
var all_labels_list = [{id: "e:1222", text: "1"}, {id: "e:1244", text: "11"}, {id: "e:1237", text: "111"}, {id: "e:1236", text: "1111"}, {id: "e:1223", text: "2"}, {id: "e:1224", text: "3"}, {id: "e:1225", text: "4"}, {id: "e:1226", text: "5"}, {id: "e:1228", text: "6"}, {id: "e:1229", text: "7"}, {id: "e:1249", text: "8"}, {id: "e:1250", text: "9"}, {id: "e:1220", text: "d"}, {id: "e:1219", text: "ds"}, {id: "e:1217", text: "dsd"}, {id: "e:1227", text: "dsddsdds"}, {id: "e:1215", text: "dsdsd"}, {id: "e:1216", text: "dsdsdsd"}, {id: "e:1232", text: "fdfdfdffdfd"}, {id: "e:1230", text: "fff"}, {id: "e:1231", text: "ffff"}, {id: "e:1221", text: "s"}, {id: "e:1218", text: "sd"}, {id: "e:1247", text: "sdsd"}, {id: "e:1243", text: "sdsdsd"}, {id: "e:1233", text: "ss"}, {id: "e:1235", text: "sss"}, {id: "e:1234", text: "ssss"}, {id: "e:1212", text: "\u0412\u0435\u0431\x2D\u0441\u0430\u0439\u0442"}, {id: "e:1242", text: "\u0432\u044B\u0432\u044B\u0432\u044B"}, {id: "e:1248", text: "\u043D\u043E\u04321"}, {id: "e:1245", text: "\u043D\u043E\u0432\u0430\u044F\x20\u043C\u0435\u0442\u043A\u0430"}, {id: "e:1246", text: "\u043D\u043E\u0432\u0430\u044F\x20\u043C\u0435\u0442\u043A\u0430\x20\u0438\u0437\x20\u0441\u043A\u0440\u044B\u0442\u043E\u0433\u043E\x20\u0438\u043D\u043F\u0443\u0442\u0430"},]; var selected_labels = [{id: "e:1222", text: "1"}, {id: "e:1244", text: "11"}, {id: "e:1237", text: "111"}, {id: "e:1236", text: "1111"},]; Как их конкатенировать сравнивая по ID (он уникальный), а повторяющемся элементам добавить: selected = true? |
|
function uniqSelected(...args){ const out = []; const map = {}; args.forEach(arr => arr.forEach(item => { const {id} = item; if(id in map) return map[id].selected = true; out.push(map[id] = {...item}); })); return out; } |
Цитата:
https://jsfiddle.net/tgue3j9w/5/ |
|
Aetae,
может else будет лучше смотреться, чем return в никуда? if(id in map) return map[id].selected = true; out.push(map[id] = {...item}); if(id in map) map[id].selected = true; else out.push(map[id] = {...item}); |
Цитата:
|
Цитата:
|
Цитата:
Тогда как если цепочка продолжается else if ... else, то "внутреннему интерпретатору"(и глазам) приходится спускаться до конца всей условной цепочки и ниже в поисках возможного продолжения, что тратит ресурс мозга.) |
Цитата:
|
Aetae, ваша философия «отбрасывания концов», которая якобы чётко и явно объявляет, что «дальше дороги нет» порождает в общем неочевидный код. Например, непонятно, куда возвращается true, если согласно сигнатуре метода forEach он не работает с возвращаемым значением. А если функции нет, то произойдёт преждевременный return. Может лучше вынести ветвление в отдельный метод?
Цитата:
function uniqSelected(...arrays) { const result = [], map = {} for(const array of arrays) for(const item of array) if(item.id in map) map[item.id].selected = true else result.push(map[item.id] = { ...item }) return result } Если всё-таки вынести в отдельный метод... если if-else вынести в отдельный метод, то «внутренний интерпретатор» Aetae будет выполнять одинаковую последовательность команд. function uniqSelected(...arrays) { const result = [], map = {} for(const array of arrays) for(const item of array) pushOrMarkAsSelected(item, result, map) return result } function pushOrMarkAsSelected(item, result, map) { if(item.id in map) map[item.id].selected = true else result.push(map[item.id] = { ...item }) } ЕЩЁ Хотя философия «отбрасывания концов» в большинстве случаев может заменена более подходящими идеями, она определённо работает, когда вам не нужно выполнение (или оно может быть завершено раннее), поскольку не подходят условия... Например... function submit() { let name, address, phone if(name = nameField.value) {} else { alert("No name to submit") return } if(address = addressField.value) {} else { alert("No address to submit") return } if(phone = phoneField.value) {} else { alert("No phone to submit") return } sendToServer(name, address, phone) } function sendToServer(name, address, phone) { // ... } |
Часовой пояс GMT +3, время: 00:53. |