Given
[1,3,1,6,22] ,
it should return
[3,6,22]
So far I have this:
const returnUniques = (array) {
if (array.length == 1) return array[0]
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i !== j) {
if (array[i] === array[j]) {
}
}
}
}
return array
}
I tried
const returnUniques = (array) {
if (array.length == 1) return array[0]
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i !== j) {
if (array[i] === array[j]) {
array.splice(i, 1)
}
}
}
}
return array
}
But it just removes duplicate and I could have this by one line with either new Set() or other techniques
So I added
const returnUniques = (array) => {
if (array.length == 1) return array[0]
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i !== j) {
if(array[i] === array[j]) {
array.splice(i,1)
array.splice(j-1, 1)
}
}
}
}
return array
}
console.log(returnUniques([1,3,1,6,22]))
because I thought that if I removed array[i] so array[j] would be at index of itself -1. But this method doesn't work if there is more than twice the same number and if many other reasons..
Maybe this nested loop isn't the best way to go ? Thanks for helps !
returnUniquesfunction, fill it with the entries that pass your test and then return the new array. Don't modify the original array.