1

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?

1
  • If this code works, and you are simply asking if there is a better approach, then this question is off topic for StackOverflow. If this is the case it would be more appropriate on codereview Commented Jul 30, 2020 at 21:53

2 Answers 2

1

You can simplify your code using reduce and map, but there aren't really any optimizations that could be made.

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

Sign up to request clarification or add additional context in comments.

Comments

0

In your ternary operator you forgot to assign the output array to expected value so it should be

 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

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)

2 Comments

downvoter please feel free to comment why my answer is incorrect, I would like to learn from my mistakes :) thanks
Looking back at this, the downvote was likely because output[i] = objx[arr[i]] > 1 ? output[i]="" : output[i]=arr[i] is redundant. The original code in the question was already correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.