为了账号安全,请及时绑定邮箱和手机立即绑定

如何获取数组中的公共值

如何获取数组中的公共值

慕的地6264312 2023-06-29 21:12:05
例如我有一个数据数组如下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"]只需要删除复制空值的公共数据。解决这个问题的最佳解决方案是什么。
查看完整描述

4 回答

?
holdtom

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);


查看完整回答
反对 回复 2023-06-29
?
海绵宝宝撒

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


查看完整回答
反对 回复 2023-06-29
?
紫衣仙女

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



查看完整回答
反对 回复 2023-06-29
?
慕神8447489

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));


查看完整回答
反对 回复 2023-06-29
  • 4 回答
  • 0 关注
  • 168 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信