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
CodePudding user response:
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)
CodePudding user response:
let arrayList = [
['p1', 'm1', 0],
['p1', 'm2', 2],
['p1', 'm3', 3],
['p2', 'm2', 3],
['p2', 'm3', 5],
['p3', 'm1', 3],
['p3', 'm2', 4]
]
const result = [];
arrayList.forEach(e =>{
let item = result.find(r=>r.panel === e[0]);
if(item){
item.content.push([e[1],e[2]]);
}else {
result.push({panel:e[0], content:[e[1], e[2]]})
}
})
console.log(result)