js 怎么将数组按照一定条件分组

得到数组: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"}

比如我在界面上获取的一个高度值为20,那么我怎么获取这个数组里面percent的值为10-30范围的值,就是我要根据我的高度将这个数组分组。这个高度值已经获取为this.scrollStop。怎么根据这个高度值计算this.scrollStop-10到this.scrollStop+10得到这个范围里面的数组?

阅读 9.5k
3 个回答

遍历这个对象数组,用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;i++){
    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;
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏