[英]Can someone tell me how to sum only some of items nested in my JavaScript array?
I am not very proud of this codeㅠㅠ I have 6000 objects in the array and would like to sum only 10 items from the array.我对这个代码不是很自豪ㅠㅠ 我在数组中有 6000 个对象,并且只想对数组中的 10 个项目求和。 Now I am putting ten coding blocks to the program.
现在我将十个编码块放入程序中。
Someone can tell me how to make it look like programing?有人可以告诉我如何使它看起来像编程吗?
<Text style={styles.text}>[{Number((items.find( x => x.id === indexTwoId+101).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+102).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+103).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+104).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+105).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+106).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+107).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+108).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+109).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+110).as==='1'?'1':'0'))}/10]</Text>
My array is as follows;我的数组如下;
count: 1,
categories: [
{id:1,as:0},
{id:2,as:0},
{id:3,as:0},
{id:4,as:0},
{id:5,as:0},
{id:6,as:0},
{id:7,as:0},
{id:8,as:0},
{id:9,as:0},
{id:10,as:0},
.
.
.
.]}```
I don't have experience with React, but in "regular" JS you might do something like this:我没有使用 React 的经验,但在“常规”JS 中你可能会做这样的事情:
let sum = items.reduce((item, total) => {
if (item.id < indexTwoId + 101 || item.id > indexTwoId + 110) return total;
if (item.as === '1') return total + 1;
return total;
}, 0)
You can probably "translate" it to a single line with ternary operators.您可能可以使用三元运算符将其“翻译”为一行。
EDIT: If you just want to count items by criteria then:编辑:如果您只想按标准计算项目,则:
items.filter(x => x.id >= indexTwoId + 101 && x.id <= indexTwoId + 110 && x.as === '1').length
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.