问题
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.
回答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
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/25216885/overwrite-duplicate-value-in-an-array-javascript