1

I have this piece of code:

var letters = ['A', 'B', 'C']
const letter1 = 'B'

for(var i=0; i<letters.length; i++) {
    var letter = letters[i]
    if (letter1 === letter) {
        console.log(letter)
        break
    } else {
        letters.push(letter1)
        break
    }
}

console.log(letters)

After running this code, I got this result:

['A', 'B', 'C', 'B']

But I want this result:

['A', 'B', 'C']

How can I do that?

2
  • 2
    Why not to allow dupes and then remove them after you finished adding things into this array? Commented Aug 17, 2020 at 11:17
  • 4
    Check if it's already in the array before pushing to it? Commented Aug 17, 2020 at 11:18

4 Answers 4

5

The simplest solution is to check if the value is in the array before pushing it:

if (!letters.includes(letter1)) letters.push(letter1)

If you want to remove duplicates from an array, you can convert it to a Set and back again:

[...new Set(letters)]

Alternatively, you could just use a Set instead of an array, which is meant for storing unique values:

const letters = new Set(['A', 'B', 'C'])
// Use add instead of push (there is no push method on Set)
letters.add(letter1)

I'm not sure why you're pushing letter1 ('B') to the array if you don't want duplicates though.

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

3 Comments

Set is the way to go
I wanted to push 'B' to check whether it already exists in the array or not.
which way is better - computation wise?
0
function removeDuplicate(payload) {
    const result = [];

    payload.forEach(function(value) {
        if(result.indexOf(value) == -1) {
            result.push(value)
        }
    })

    return value
}

1 Comment

Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users also with similar issues.
0

Check if array has the element before inserting.

Array.proptotype.includes() will help

if(!extingArray.includes(element)) {
    existingArray.push(element)
}

Comments

0

Use letters.pop() to remove any duplicates that might get entered into the end of the array.

Comments

Your Answer

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