-1

I have read some partially solutions on my problem but unfortunately I've come up for questioning. So here's my question. I have an array var = results[1,2,2,3,1,3]. I have to print/echo all the values and the final values should be display the value of 1,2,3. I've read about finding values that has a duplicate but this might not work on mine since it only returns duplicate values. I've read about filtering unique values but of course it will only show me a unique value and won't show me the others. And one of the comments there suggests this and absolutely maybe an exact solution:

_.uniq([1, 2, 1, 3, 1, 4]);

=> [1, 2, 3, 4]

the link is HERE...

But I don't know how to use it correctly. Is it applicable to my problem?

Here's my fiddle anyway.

Community
  • 1
  • 1
AlexJaa
  • 389
  • 7
  • 20

3 Answers3

1

Try this

    var getfruits = [1, 2, 2, 3, 1, 3];
    var newfruits = [];
    $.each(getfruits, function (i, el) {
        if ($.inArray(el, newfruits) === -1) newfruits.push(el);
    });
    console.log(newfruits)
    alert(newfruits[0]);
    alert(newfruits[1]);
    alert(newfruits[2]);

DEMO

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
1

Here is the very simple implementation using js

var getfruits = [1, 2, 2, 3, 1, 3];
var uniq = [];
for (var i = 0; i < getfruits.length; i++) {
    if(uniq.indexOf(getfruits[i])==-1)
        uniq.push(getfruits[i]);
};

console.log(uniq);

And you have to just add lo-dash in your fiddle.

FIXED FIDDLE WITH LO-DASH

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • @Alexdn here is your fixed fiddle with lo-dash, I've updated in my answer also. http://jsfiddle.net/mkdskd/3e8tcv02/9/ – Mritunjay Aug 09 '14 at 09:12
  • One more sir. This is actually the problem: http://jsfiddle.net/frLdf32L/79/. Why displays me `1,2,2`? instead of `1,2,3`? – AlexJaa Aug 09 '14 at 09:29
  • If you notice, I want to store all values taken from `option` tag to an array. Then make again a new array to store the filtered duplicate value. And for final step is to append a textbox that has a value of those three. And I think I can do that. If the last problem will be solve. – AlexJaa Aug 09 '14 at 09:36
  • 1
    include jQuery it says `$` is not defined. – Mritunjay Aug 09 '14 at 09:48
1

Try this

var arr = [1, 2, 2, 3, 1, 3];
var newarr = [];
$.each(arr, function (index, element) {
    if ($.inArray(element, newarr) < 0) newarr.push(element);
});

alert(newarr[0]);
alert(newarr[1]);
alert(newarr[2]);

Demo

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122