简体   繁体   中英

Display array data only one time

I have an array which looks like below -

const arr = [{name: 'ST', value: 1}, {value: 0}, {name: 'ST', value: 2}]

I'm looping over above arr with the map function and able to display the value.

But the problem is I want to display name only single time. For eg ST: 3 .

So ST will display single time and we will do the addition of all the value. Also I dont know the index of name at which index it is available.

Is there any other alternative for this rather doing hardcode name .

Thanks in advance.

map returns an array and not suitable in your use case. You can use forEach , reduce or normal for-loop . The below code achieves the result using reduce . Inside callback function sum all the values.

 const arr = [{ name: 'ST', value: 1 }, { name: 'ST', value: 0 }, { name: 'ST', value: 2 }].reduce((acc, curr) => { if (.acc[curr.name]) { acc[curr.name] = curr;value. } else { acc[curr.name] += curr;value } return acc, }; {}). console.log(arr)

You can easily achive this using reduce

 const arr = [{ name: "ST", value: 1 }, { value: 0 }, { name: "ST", value: 2 }]; const result = arr.reduce((acc, curr) => { const { name, value } = curr; const tempSearchObj = acc.find((o) => o.name === name); if (tempSearchObj) { tempSearchObj.value = value + tempSearchObj.value; } else { if (name) acc = [...acc, { name, value }]; else acc = [...acc, { value }]; } return acc; }, []); console.log(result);

First of all when you use Array.map the length of the output array will be same as the length of the input array . So, that is not the desired method that you want.

There are multiple ways in achieving the desired output. As you want to display the sum of all the values where you've the same name then Array.reduce will come to the rescue.

 const arr = [{name: 'ST', value: 1}, {value: 0}, {name: 'ST', value: 2}] const formatArr = arr => { return Object.values(arr.reduce((res, obj) => { //Check if the object is already present in the accumulator ie, res //If so, add he current obj.value to the existing value if(res[obj.name]) { res[obj.name].value += obj.value; } else { //else create a new object and add it the accumulator res[obj.name] = {...obj} } return res; }, {})); } //Get the formatted array with cumulative values based on name const formattedOutput = formatArr(arr); //Use loop to print values. //If you are using react you can use `map` to display in the UI. //For simplicity here i'm using `forEach` to display in the console. formattedOutput.forEach(obj => { console.log(`${obj.name || "Name"}: ${obj.value}`); })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM