[英]Remove duplicates and replace from an array
I have an array of elements:我有一个元素数组:
arr = ["one", "two", "three", "one", "two", "one"]
I want to replace duplicates with empty strings in array:我想用数组中的空字符串替换重复项:
output= ["", "", "three", "", "", ""]
Here is my code:这是我的代码:
let obj = {}
for(let i=0; i<arr.length; i++) {
let a = arr[i];
if(obj[a]) obj[a]+=1
else obj[a]=1
}
let output = []
for(let i=0; i<arr.length; i++) {
output[i] = obj[arr[i]] > 1 ? "" : arr[i];
}
Is this a better approach or is there a way to improve the performance?这是更好的方法还是有办法提高性能?
You can simplify your code using reduce
and map
, but there aren't really any optimizations that could be made.您可以使用reduce
和map
来简化您的代码,但实际上并不能进行任何优化。
let arr = ["one", "two", "three", "one", "two", "one"]; let freq = arr.reduce((acc,curr)=>(acc[curr] = (acc[curr] || 0) + 1, acc), {}); let res = arr.map(x=>freq[x] === 1? x: ''); console.log(res);
In your ternary operator you forgot to assign the output array to expected value so it should be在您的三元运算符中,您忘记将 output 数组分配给预期值,因此它应该是
output[i] = objx[arr[i]] > 1 ? output[i]="" : output[i]=arr[i]
arr = ["one", "two", "three", "one", "two", "one"] obj = {} for(let i=0; i<arr.length; i++) { let a = arr[i]; if(obj[a]) obj[a]+=1 else obj[a]=1 } let output = [] for(let i=0; i<arr.length; i++) { output[i] = obj[arr[i]] > 1? output[i]="": output[i]=arr[i] } console.log(output)
Here is a different simpler approach using foreach
and map
这是使用foreach
和map
的另一种更简单的方法
arr = ["one", "two", "three", "one", "two", "one"] var obj = {}; arr.forEach(e => { obj[e] = obj[e] || 0 obj[e] = obj[e] + 1 }) res= arr.map(x => obj[x] > 1? "": x) console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.