Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript array if one element same takes another element in array

I want to convert one array to new format

This is my array

let data = [
 { operatorName: 'MBC', negativeTotal: -5873, postiveTotal: 15632 },
 { operatorName: 'OSEN+', negativeTotal: -4071, postiveTotal: 2206 }
];

Here I want to covert data to this format

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected Array result:

[
    {
        data : [2206, -4071],
        label:'OSEN+'
    },
    {
        data : [15632,-5873],
        label:'MBC'
    }
];

I tried this code:

const uniqueOperators = [...new Set(data.map((x) => x.operatorName))];
let d = []
let dataset = uniqueOperators.map((uniqueOperator) => {
  
  data.find((item)=>{
    if(item.operatorName === uniqueOperator){
      console.log(item)
    }
    
  })
});

But it is not coming what my expected array result.

>Solution :

This would also work. Same as @Mamun’s answer with destructuring the items:

let data = [
  { operatorName: "MBC", negativeTotal: -5873, postiveTotal: 15632 },
  { operatorName: "OSEN+", negativeTotal: -4071, postiveTotal: 2206 },
];

const output = data.map(({ operatorName, negativeTotal, postiveTotal }) => ({
  data: [postiveTotal, negativeTotal],
  label: operatorName,
}));

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading