2
\$\begingroup\$

If i have a object like following

result = [
 {
 phones : ["ABC", "DEF"],
 name: "Simon"
 },
 {
 phones : ["ABC", "XZY"],
 name: "John"
 }
]

Expected output

Map of key, value

{ABC, ["Simon", "John"]}
{DEF, ["Simon"]}
{XYZ, ["John"]}

My try

map: Map = new Map(); 
for ( r of result ) {
 for( phone of r.phones) {
 if(map.get(phone)){
 map.set(phone, map.get(phone).concat(r.name))
 } else {
 map.set(phone, r.name);
 }
 }
}

Is there a ES6 way to perform the above double iteration in a minimised way ?

asked Oct 13, 2020 at 14:44
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Overall Your code is quite reasonable, after fixing something that looks to be a typo. The transformation that needs to be applied to the data structure isn't entirely trivial, so the logic that needs to be implemented requires a handful of lines of code.

Typo? But your code also has a typo/bug: the map.set(phone, r.name); will set the value in the map to be a string, not an array. You probably meant to do map.set(phone, [r.name]); (maybe a miscopy?) There's also map: Map = new Map();, which isn't valid syntax in JS, remove the : Map part.

Conditional operator If you wanted to shorten your existing code, see how you're using .map.set(phone, someExpression) depending on a condition - this is a sign that you can use the conditional operator instead of the if/else.

map.set(phone, (map.get(phone) ?? []).concat(r.name));

But while that makes the code shorter, is it easier to read? I'm not entirely convinced. Maybe you'll like it, or maybe you won't.

There are a few other things that can improve the code quality:

Declare your variables Doing for (r of result) will implicitly create a global r variable and put it on the global object. If you're running in strict mode, this will throw an error too. Always declare variables before using them, preferably with const.

Destructure? With for (r of result) or for (const r of result), you create a variable named r, which isn't so intuitive - what's an r? Maybe destructure the name and phones properties immediately.

const result = [
 {
 phones : ["ABC", "DEF"],
 name: "Simon"
 },
 {
 phones : ["ABC", "XZY"],
 name: "John"
 }
]
const map = new Map();
for (const { phones, name } of result) {
 for (const phone of phones) {
 map.set(phone, (map.get(phone) ?? []).concat(name));
 }
}
console.log([...map]);

answered Oct 13, 2020 at 15:04
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.