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]

Tushar
  • 85,780
  • 21
  • 159
  • 179
Ramesh Khadka
  • 484
  • 1
  • 7
  • 19
  • 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. – nnnnnn Nov 03 '15 at 05: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). – Gaurav Gupta Nov 03 '15 at 05:46
  • http://stackoverflow.com/a/14438954/2609085 – Gaurav Gupta Nov 03 '15 at 06:07

1 Answers1

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

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80