Avellino
Avellino

Reputation: 89

Format output of an array map

I am trying to make a function that counts duplicates, this works but not in the output format I need. This is my function:

    var duplicateCount = {};
    countryArray.forEach(e => duplicateCount[e] = duplicateCount[e] ? duplicateCount[e] + 1 : 
    1);
     result5 = Object.keys(duplicateCount).map(e => {return {key:e, count:duplicateCount[e]}});
    console.log("result5", result5);

The output I get is:

    result5 
    (3) [{…}, {…}, {…}]
    0: {e: "CRM", count: 6}
    1: {e: "TSA", count: 8}
    2: {e: "PCS", count: 3}
    length: 3
    __proto__: Array(0)

The output I need is:

    result5 
    (3) [{…}, {…}, {…}]
    0: {"CRM", 6}
    1: {"TSA", 8}
    2: {"PCS", 3}
    length: 3
    __proto__: Array(0)

Any help is good. Thank!!

Upvotes: 0

Views: 476

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Use Object.enties and map

countryArray = ["foo", "bar", "foo"];
var duplicateCount = {};

countryArray.forEach((e) => (duplicateCount[e] = (duplicateCount[e] ?? 0) + 1));

result5 = Object.entries(duplicateCount).map(([key, value]) => ({
  [key]: value,
}));

console.log("result5", result5);

Upvotes: 0

Pavlos Karalis
Pavlos Karalis

Reputation: 2976

Did you mean you want the e property to be the key? (it shows a , instead of :)

const data = [
   {e: "CRM", count: 6},
   {e: "TSA", count: 8},
   {e: "PCS", count: 3}
  ]
     

const output1 = data.map(obj => ({[obj.e]:null, [obj.count]:null}))

const output2 = data.map(obj => ({[obj.e]:obj.e, [obj.count]:obj.count}))

const output3 = data.map(obj => ([obj.e, obj.count]))



console.log("output1:",output1, "output2:",output2, "output3:",output3)

Upvotes: 1

oleksiisedun
oleksiisedun

Reputation: 529

I assume you need an array of objects. But {"CRM", 6} is incorrect object syntax. The object should contain key: value pairs.

Upvotes: 0

Related Questions