猿问

如何获取数组中的公共值

例如我有一个数据数组如下

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"]

我需要在 javascript 中列出与下面相同的数据

var arrDataSorted = ["40-25","50-48","30-25","40-23","40-45","40-50","40-50"]

只需要删除复制空值的公共数据。

解决这个问题的最佳解决方案是什么。


慕的地6264312
浏览 169回答 4
4回答

holdtom

您可以尝试使用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);

海绵宝宝撒

您可以从数组创建一个集合,该集合将自动删除重复项: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];

紫衣仙女

将此函数添加到您的代码中:function removeCommonValues(arr) {&nbsp; let result = [];&nbsp; for(let i=0; i < arr.length-1; ++i) {&nbsp; &nbsp; if(result.includes(arr[i]) === false && arr[i] !== null)&nbsp; &nbsp; &nbsp; result.push(arr[i])&nbsp; }&nbsp; 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"]

慕神8447489

该函数可以位于单独的文件中,以便在多个页面之间重用。然后您可以调用该函数来过滤不为空的不同值。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;&nbsp;}console.log(arrData.filter(fn));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答