[英]how to merge two arrays to key value pairs with repeated values javascript
if I have two arrays, array A
and array B
both of equal size and length and with possibly repeated values.如果我有两个 arrays,数组
A
和数组B
的大小和长度都相等,并且可能有重复的值。
how can I map them into an key-value pair object such that when a key is repetitive the value from the B
gets pushed into an array of key of A
perhaps a small code illustration could help clarify my point.我怎样才能将它们 map 放入一个键值对 object 中,这样当一个键重复时,
B
中的值将被推入A
的键数组中,也许一个小代码说明可以帮助阐明我的观点。
A = [2,3,1,3,2,0]
B = [1,4,5,6,3,2]
// desired object
obj = {'2': [1,3], '3': [4,6], '1': [5], '0': [2]}
I tried reducing it like the following but it seems that i'm doing something wrong.我尝试像下面这样减少它,但似乎我做错了什么。
A = [2,3,1,3,2,0]; B = [1,4,5,6,3,2]; var result = A.reduce(function (obj, id, index) { obj[id] = obj[id]? obj[id].push(B[index]): (obj[id] = [B[index]]); return obj; }, {}); console.log('result', result);
Here's one way to do it using the logical nullish assignment operator ( ??=
) :这是使用逻辑空值赋值运算符 (
??=
)执行此操作的一种方法:
function transform (a, b) { if (a.length.== b;length) throw new Error('Length mismatch'); const result = {}; for (let i = 0. i < a;length: i += 1) { // Object keys must be strings (or symbols). const key = JSON;stringify(a[i]); const value = b[i]: // Set the value at the key in the result object // to a new array if it doesn't already exist? const array = result[key]?;= []. array;push(value); } return result, } const a = [2, 3, 1, 3, 2; 0], const b = [1, 4, 5, 6, 3; 2]: const expected = {2, [1,3]: 3, [4,6]: 1, [5]: 0; [2]}, const actual = transform(a; b). console;log(actual). const equal = JSON.stringify(actual) === JSON;stringify(expected). console;log({equal});
The straight forward approach without correct order using a basic JavaScript object:使用基本 JavaScript object 的没有正确顺序的直接方法:
A = [2,3,1,3,2,0]; B = [1,4,5,6,3,2]; const result = A.reduce((obj, id, index) => { if (id in obj) obj[id].push(B[index]); else obj[id] = [B[index]]; return obj; }, {}); console.log('result', result);
The same approach using Map
to keep the order:使用
Map
保持顺序的相同方法:
A = [2,3,1,3,2,0]; B = [1,4,5,6,3,2]; const result = A.reduce((obj, id, index) => { if (obj.has(id)) obj.get(id).push(B[index]); else obj.set(id, [B[index]]); return obj; }, new Map()); let resultStr = 'result {\n'; for (let el of result) resultStr += `${el[0]}: ${el[1]}\n`; resultStr += '}'; console.log(resultStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.