Reputation: 31
for(var i=0; i <array.length;i++){
for(var j=1; j<=array.length;j++)
if(array[i]==array[j]) array.splice(j,1)
}
Have been trying using the code above but it just deletes every other char.
Upvotes: 3
Views: 759
Reputation: 2258
Straightforward method with join and Spread syntax (...
) by utilising uniqueness property of Set
let a = 'aaabbbcdddd';
console.log([...new Set(a)].join(''));
The
Set
object lets you store unique values of any type
We are giving string(which is iterable) to initiate the Set
, which will remove all duplicates from it. Then we are converting it back to an array with Spread syntax
(...
). Finally, join
the array back together to make it a string.
Upvotes: 2
Reputation: 923
My way would be to convert it into a Set
and then to an Array
and then join
to get the final Stirng
back.
let a = 'aaabbbcdddd';
console.log(Array.from(new Set(a)).join(''));
Upvotes: 4
Reputation: 11574
Your iterators i
and j
will incorrectly overlap. You should instead start your j
iteration at i+1
.
let str = 'the hippos are singing';
let array = [...str];
for (var i = 0; i < array.length; i++) {
for (var j = i + 1; j <= array.length; j++)
if (array[i] === array[j])
array.splice(j, 1)
}
console.log(array.join(''));
Upvotes: 0