Home > OS >  How to sum value in array im JavaScript?
How to sum value in array im JavaScript?

Time:11-06

I have two array object, and i put that two array to make a chart in Vue JS 3

array 1 is for the title:

[
    "Jumlah SD",
    "Jumlah SMP",
    "Jumlah SD",
    "Jumlah SMP"
]

and second array is the value:

[
    "22",
    "243",
    "44",
    "22"
]

My question is, how to sum the second array? My expected array object is: first array for title:

[
    "Jumlah SD",
    "Jumlah SMP",
]

and second array for value will be:

[
    "66",
    "265",
]

My current code is:

        onMounted(() => {
            chart.totalField = props.datas.length === 0 ? 0 : JSON.parse(props.datas[0].fieldDatas).length
            chart.totalData = props.datas.length

            if (chart.total !== 0) {
                for (let i = 0; i < chart.totalData; i  ) {
                    for (let j = 0; j < chart.totalField; j  ) {
                        chart.title.push(JSON.parse(props.datas[i].fieldDatas)[j].title)
                        chart.value.push(JSON.parse(props.datas[i].fieldDatas)[j].value)
                    }
                }
            }
            console.log(chart.title);
            console.log(chart.value);
        })

CodePudding user response:

You can use reduce method, to group the by the items in the arr1 with sum of arr2

const arr1 = [
    "Jumlah SD",
    "Jumlah SMP",
    "Jumlah SD",
    "Jumlah SMP"
]

const arr2 = [
    "22",
    "243",
    "44",
    "22"
]

const result = arr1.reduce((acc, item, index) => {
  let value = acc[item];
  let count =  arr2[index]; 
  return {
    ...acc,
    [item]: value ? value  = count : count
  }
}, {})

console.log(result)
console.log(Object.values(result))
console.log(Object.keys(result))

CodePudding user response:

I would data-massage the data from the array into an object:

  let obj = { };
  obj = { "Jumlah SD": 22 }; // index = 0
  obj = { "Jumlah SD": 22, "Jumlah SMP": 243}; // index = 1
  obj = { "Jumlah SD": 66, "Jumlah SMP": 243}; // index = 2
  obj = { "Jumlah SD": 66, "Jumlah SMP": 265}; // index = 3
  Object.keys(obj); // [ "Jumlah SD", "Jumlah SMP" ]
  Object.values(obj); // [ 66, 265 ]

Note I haven't supplied the Javascript to achieve the above, but, I think it would be straightforward to design a for loop that populates obj Object as per above.

CodePudding user response:

Try this:

const arr1 = [
    "Jumlah SD",
    "Jumlah SMP",
    "Jumlah SD",
    "Jumlah SMP"
];

const arr2 = [
    "22",
    "243",
    "44",
    "22"
];

dict = {}

for (let i = 0; i < arr1.length; i  ) {
    const key = arr1[i];
    if (key in dict) {
        dict[key] = String(Number(dict[key])   Number(arr2[i]));
    } else {
        dict[key] = String(Number(arr2[i]));
    }
}

const arr3 = Object.keys(dict);
const arr4 = Object.values(dict);
  • Related