我有一个Objects数组,我想把它添加到一个特定的索引中,而且只有当它是 visible:true
在另一个数组中。
我已经尝试了以下代码。
let arrVal = []
let arr = [
{ id:456,indexValue:2,isVisible:true},
{ name:"xyz",indexValue:3,isVisible:true},
{ age:21,indexValue:5,isVisible:true},
{ gender:"male",indexValue:1,isVisible:false},
{ city:"new york",indexValue:0,isVisible:false},
{ country:"usa",indexValue:4,isVisible:true}
]
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
if(element.isVisible === true){
arrVal.splice(element.indexValue,0,element)
}
}
console.log("Values : " , arrVal)
任何帮助将是巨大的。
谢谢你的帮助。
基于 本回答 对结果数组进行单行排序。
arrVal.sort((a,b) => (a.indexValue > b.indexValue) ? 1 : ((b.indexValue> a.indexValue) ? -1 : 0));