簡體   English   中英

僅顯示一次數組數據

[英]Display array data only one time

我有一個如下所示的數組 -

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

我正在使用map function 遍歷arr並能夠顯示該值。

但問題是我只想一次顯示名稱。 例如ST: 3

所以ST將顯示單個時間,我們將添加所有值。 另外我不知道它在哪個索引處可用的名稱索引。

有沒有其他替代方法可以代替硬編碼name

提前致謝。

map返回一個數組,不適合您的用例。 您可以使用forEachreduce或普通for-loop 下面的代碼使用reduce實現了結果。 內部回調 function 對所有值求和。

 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)

您可以使用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);

首先,當您使用Array.map時, output array的長度將與input array的長度相同。 因此,這不是您想要的方法。

有多種方法可以實現所需的 output。 當您想要顯示您具有相同name的所有values的總和時, Array.reduce將來救援。

 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}`); })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM