0

Below is my data and array of ids ,That i have to get their sums but i have no idea how to go about it

any one who can help me write function to return sum .Thanks.

 const data = [
    { label: 'Excess Protector_Ksh10000', value: '1000', id: '1' },
    { label: 'Political Violence  and Terrorism_ksh5000', value: '5000', id: '2' },
    { label: 'Excess Protector(Material Damage)_ksh5000', value: '5000', id: '3' },
    { label: 'Theft of Car Accessories(Jack,spanners,etc)_Ksh1500', value: '15000', id: '4' },
    { label: 'Loss of Use 10Days_Ksh3000', value: '3000', id: '5' },
    { label: 'Loss of Use 20Days_Ksh5000', value: '5000', id: '6' },
  ];

const ids = ["1", "2", "4"];


I have no idea , am just new in react framework

derpirscher
  • 14,418
  • 3
  • 18
  • 35
Ramos
  • 33
  • 4

1 Answers1

0

use the reduce function

 const data = [
    { label: 'Excess Protector_Ksh10000', value: '1000', id: '1' },
    { label: 'Political Violence  and Terrorism_ksh5000', value: '5000', id: '2' },
    { label: 'Excess Protector(Material Damage)_ksh5000', value: '5000', id: '3' },
    { label: 'Theft of Car Accessories(Jack,spanners,etc)_Ksh1500', value: '15000', id: '4' },
    { label: 'Loss of Use 10Days_Ksh3000', value: '3000', id: '5' },
    { label: 'Loss of Use 20Days_Ksh5000', value: '5000', id: '6' },
  ];

const ids = ["1", "2", "4"];

const sum = data.reduce((acc, item) => {
    if(ids.includes(item.id)){
      return acc + Number(item.value)
    }
    return acc
}, 0)

console.log(sum)
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80