Reputation: 9
I'm trying to remove duplicates from this random generator array. I've tried many different lines of codes that could remove duplicates but I haven't been able to get anything to work.
example of what I've used:
filtered = idArray.filter(function (str) { return str.indexOf(idArray) === -1; });
The code:
var idArray = ['img1', 'img2'];
var newID=getRandomInt(2);
var newCube=idArray[newID];
document.getElementById(""+newCube+"").src="assets/button-yellow_x64.png";
document.getElementById(""+newCube+"").src="assets/button-yellow_x64.png";
Upvotes: 0
Views: 477
Reputation: 39270
To remove doubles you can do the following:
//remove doubles from an array of primitive values
console.log(
"no doubles primitive values",
[1,2,3,4,3,4,5,6,7,7,7,8,9,1,2,3,4].filter(
(value,index,all)=>all.indexOf(value)===index
)
);
//remove doubles from an array of references you can do the same thing
const one = {id:1}, two = {id:2}, three = {id:3};
console.log(
"no doubles array of references",
[one,two,one,two,two,one,three,two,one].filter(
(value,index,all)=>all.indexOf(value)===index
)
);
//remove doubles from an array of things that don't have the same reference
// but have same values (say id)
console.log(
"no doubles array of things that have id's",
[{id:1},{id:1},{id:1},{id:2},{id:3},{id:2}].reduce(
([all,ids],item,index)=>
[ all.concat(item), ids.concat(item.id) ],
[[],[]]
).reduce(
(all,ids)=>
all.filter(
(val,index)=>ids.indexOf(val.id)===index
)
)
);
Or you could just create a shuffled array without doubles:
const shuffle = arr => {
const recur = (result,arr) => {
if(arr.length===0){
return result;
}
const randomIndex = Math.floor(Math.random() * arr.length);
return recur(
result.concat([arr[randomIndex]]),
arr.filter((_,index)=>index!==randomIndex)
);
};
return recur([],arr);
}
const array = [1,2,3,4,5];
const shuffled = shuffle(array);
console.log("array is:",array,"shuffled array is:",shuffled);
Upvotes: -1
Reputation: 33171
Using sets are the newer and best answer, but if you still wanted to implement your requirement, you could use an object hash to keep track of items, and then just get the keys. For example:
var idArray = ["img1", "img2", "img1", "img2"]
var hash = {}
idArray.forEach(id => hash[id] = true)
var ids = Object.keys(hash)
console.log(ids)
Upvotes: 1
Reputation: 5853
You can use Set in new ES6 which will filter redundant elements and typecast that later into an array.
var idArray = ["img1", "img2", "img1", "img2"];
var distinctArray = [...new Set(idArray)];
console.log(distinctArray);
Upvotes: 2