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

Update an array into filter a new array

Having a array values of the below need to convert another form of array using typescript or javascript.

arrayList = {
['p1', 'm1', 0], 
['p1', 'm2', 2], 
['p1', 'm3', 3], 
['p2', 'm2', 3], 
['p2', 'm3', 5], 
['p3', 'm1', 3],
['p3', 'm2', 4]}

new array need to check with first element of array

array2 = { [ panel: 'p1', content: {['m1',0], ['m2', 2], ['m3', 3]}],
[ panel: 'p2', content: {['m2', 3], ['m3', 5]}],
[ panel: 'p3', content: {['m1', 3], ['m2', 4]}]  }

Thanks in advance

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

>Solution :

As I said in the comment,both arrayList and array2 are not in valid json format.

If changed them to valid json format such as below

let arrayList = [
['p1', 'm1', 0], 
['p1', 'm2', 2], 
['p1', 'm3', 3], 
['p2', 'm2', 3], 
['p2', 'm3', 5], 
['p3', 'm1', 3],
['p3', 'm2', 4]
]

array2 = { [ panel: 'p1', content: [['m1',0], ['m2', 2], ['m3', 3]]],
[ panel: 'p2', content: [['m2', 3], ['m3', 5]]],
[ panel: 'p3', content: [['m1', 3], ['m2', 4]]]  }

then you can use below code to do it

let arrayList = [
['p1', 'm1', 0], 
['p1', 'm2', 2], 
['p1', 'm3', 3], 
['p2', 'm2', 3], 
['p2', 'm3', 5], 
['p3', 'm1', 3],
['p3', 'm2', 4]
]

let result = arrayList.reduce((a,c) =>{
  let obj = a.find(i => i.panel == c[0])
  if(obj){
    obj.content.push(c.slice(1))
   }else{
    obj ={'panel':c[0],'content':[c.slice(1)]}
    a.push(obj)
   }
  return a
},[])

console.log(result)
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