4 回答
TA贡献1805条经验 获得超10个赞
您可以尝试使用Array.prototype.filter()
删除空值并Set
获取唯一值。最后使用 来Spread syntax (...)
将集合结果转换为数组。
尝试以下方法:
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
var arrDataSorted = [...new Set(arrData.filter(i => i))];
console.log(arrDataSorted);
TA贡献1809条经验 获得超8个赞
您可以从数组创建一个集合,该集合将自动删除重复项:
let arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
let set = new Set(arrData);
这仍然会保留 null,您可以通过调用将其删除delete,并使用扩展运算符将其转换回数组...。最终代码将是:
let set = new Set(arrData);
set.delete(null);
let distinctArr = [...set];
TA贡献1839条经验 获得超15个赞
将此函数添加到您的代码中:
function removeCommonValues(arr) {
let result = [];
for(let i=0; i < arr.length-1; ++i) {
if(result.includes(arr[i]) === false && arr[i] !== null)
result.push(arr[i])
}
return result
}
用法:
removeCommonValues(["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]) // Return ["40-25", "50-48", "30-25", "40-23", "40-45", "40-50"]
TA贡献1780条经验 获得超1个赞
该函数可以位于单独的文件中,以便在多个页面之间重用。然后您可以调用该函数来过滤不为空的不同值。
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
function fn(value,index,self){
return self.indexOf(value) === index && value;
}
console.log(arrData.filter(fn));
添加回答
举报