reactjs 删除数组中重复的字符串格式的数字?

3mpgtkmj  于 2023-05-28  发布在  React
关注(0)|答案(4)|浏览(139)

我有一个代码片段,比如如何从和数组中删除重复项。我尝试使用过滤器的方法,但它的工作只有数字,但我的数组包含字符串格式的数字。所以我很困惑如何解决它。

// javascript

// output = [1,2,3,4,5,6,7]

const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];

const result = arr1.filter((item, index) => arr1.indexOf(item) === index)

//console.log(result);

// my result 

// [1, 2, "1", 3, 4, "3", 5, 6, 7, "5"]

// But output should be = [1,2,3,4,5,6,7]
velaa5lx

velaa5lx1#

您可以将字符串解析为带有parseInt(item)的数字,然后比较它们。这段代码将把字符串解析为Int,然后过滤这些字符串。

let arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];

arr1 = arr1.map(m => parseInt(m));

const result = arr1.filter((item, index) => arr1.indexOf(item) === index)

console.log(result);
mklgxw1f

mklgxw1f2#

你可以使用Number()将字符串转换为数字,然后过滤它,下面是一个参考

const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];

const filterArr = (data) =>{
  data = data.filter((e, i) => data.indexOf(Number(e)) === i)
  return data
}

console.log(filterArr(arr1))
enyaitl3

enyaitl33#

const arr = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];

const tempArr = arr.map(val => Number(val));

const result = Array.from(new Set(tempArr));

console.log(result) // [1, 2, 3, 4, 5, 6, 7]
vc6uscn9

vc6uscn94#

考虑:

const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];

const result = [...new Set(arr1.map(Number))]

console.log(result);

这样做的是:

  • 将所有内容转换为数字(map(Number)
  • 将数组转换为Set(表示没有重复)
  • 将该集合转换回[...]数组

相关问题