0

Here is a simple javascript code that adds unique data from one array to another.

var data = [1, 2, 3, 2]
var dump = [];
for (var i = 0; i < data.length; i++) {
    if (dump.length == 0) {
        dump.push(data[i])
    } else {
        for (var a = 0; a < dump.length; a++) {
            if (dump[a] != data[i]) {
                if (a >= dump.length) {
                    dump.push(data[i])
                }
            }
        }
    }
}

I only get 1 item from the data array : [1] instead of [1,2,3]

3
  • 1
    Use pencil and paper to work your way through that algorithm and you'll see that (a >= dump.length) ain't ever going to be true. Commented Nov 3, 2015 at 5:44
  • Answer is not the only key, but approach is important. So I suggest you to put console.log statement and just debug it because it looks like you are missing something (in terms of programming logic). Commented Nov 3, 2015 at 5:46
  • stackoverflow.com/a/14438954/2609085 Commented Nov 3, 2015 at 6:07

1 Answer 1

1

That's becuase this line

if (a >= dump.length) {
    dump.push(data[i])
}

You pushed data when a is greater then or equal to dump.length

but in your loop

a < dump.length

It won't make it there

Try like this

for (var a = 0; a < dump.length; a++) {
    if (dump[a] == data[i]) { // when found break there
        break;
    }
}
if (a == dump.length) // if nothing found loop will be fully executed
    dump.push(data[i]);

JSFIDDLE

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

2 Comments

I wanted to push the data item into the dump array only when all the dump item is checked so a >= dump.length is used. I suppose a will be incremented by 1 greater than dump.length at the end of loop (a++)
check my fiddle @RameshKhadka

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.