if I have two arrays, array A
and array B
both of equal size and length and with possibly repeated values.
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.
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:
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:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.