Reputation: 303
I want to write array elements only one time. Such as if i want to write 3 it should write once only. Is it possible achiving it using array.
my code
var arr = [ 1,1,1,1,1,1,1,1,3,3,3,3,3,3,4,4,4,4];
arr = $.grep(arr, function( x, y ) {
return ( x !== 1);
});
$( "p>span" ).text( arr.join( ", " ) );
DEMO;
Upvotes: 2
Views: 73
Reputation: 12300
Oh well - I am little bit too late. But here's an alternative - if you are using underscore.js:
_.uniq([1,1,1,1,1,1,1,1,3,3,3,3,3,3,4,4,4,4]);
Or use a filter:
var unique=a.filter(function(itm,i,a){
return i==a.indexOf(itm);
});
Upvotes: 1
Reputation: 4436
Your code updated here jsfiddle ..
function eliminateDuplicates(arr) {
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
out.push(i);
}
return out;
}
Upvotes: 0
Reputation: 28823
Try like this
var arr = [1,1,1,1,2,2,2,2,2,3,3,1,1];
var sorted_arr= arr.sort();
var newArr= [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
newArr.push(sorted_arr[i]);
}
}
Hope it helps.
Upvotes: 0
Reputation: 82231
Try this:
var result = [];
$.each(arr, function(i, e) {if ($.inArray(e, result) == -1) result.push(e);});
return result;
Upvotes: 0
Reputation: 337560
Assuming that you mean that you want to remove duplicate values from your array you can use the $.unique
helper in jQuery:
var arr = [1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4];
$("p > span").text($.unique(arr));
Upvotes: 5