How does js group arrays according to certain conditions
get the array: this.dataBarrage = res.list
list:[
0:{id: "1", content: "ddddd", percent: "60"}
1:{id: "1", content: "ddddd", percent: "30"}
2:{id: "2", content: "", percent: "0"}
3:{id: "3", content: "", percent: "10"}
4:{id: "4", content: "Qwery", percent: "0"}
for example, if I get a height value of 20 on the interface, how do I get the value of percent in this array in the range of 10-30, that is, I want to group the array according to my height. This height value has been obtained as this.scrollStop. How to calculate this.scrollStop-10 to this.scrollStop+10 according to this height value to get the array in this range?
iterate through the array of objects, using array.filter
.
let list=[
{id: "1", content: "ddddd", percent: "60"},
{id: "1", content: "ddddd", percent: "30"},
{id: "2", content: "", percent: "0"},
{id: "3", content: "", percent: "10"},
{id: "4", content: "Qwery", percent: "0"},
]
let height=20
list=list.filter(e=>{
return parseInt(e.percent)<=(height+10)&&parseInt(e.percent)>=(height-10)
})
console.log(list)
var list=[{id: "1", content: "ddddd", percent: "60"},
{id: "1", content: "ddddd", percent: "30"},
{id: "2", content: "", percent: "0"},
{id: "3", content: "", percent: "10"},
{id: "4", content: "Qwery", percent: "0"},
{id: "5", content: "ddddd", percent: "80"},
{id: "6", content: "ddddd", percent: "90"},
{id: "7", content: "ddddd", percent: "50"},
]
function search(data,key,offset,val){
var newArr=[];
for(var i=0;i<data.length;iPP){
var k = parseInt(data[i][key]);
if(val>=(k-offset)&&val<=(k+offset))
newArr.push(data[i]);
}
return newArr;
}
search(list,'percent',10,20); //
list.filter(e=>{
return Math.abs(e.percent-20)<=10;
})