I'll try my best to explain my problem. In my application I have a section that lists all users with a name and image. When adding a new user, the profile picture is taken from an array of default pictures and it has to be different from image of the other users. Down below there is my solution and it seems to work, but im searching for a cleaner way to do it.
Thank you!
const profileImages = [img1, img2, img3, img4];
let users = [
{
name: "Username1",
image: img1
},
{
name: "Username2",
image: img2
}
];
/*
This array will fill up with the images not already taken by other users,
and I'll randomly pick from these to assign it to the new user
*/
let availableImages = [];
users.forEach(user =>{
if (availableImages.length === 0)
{
availableImages = profileImages.filter(image => image !== user.image);
}
else
{
availableImages = availableImages.filter(image => image !== user.image);
}
});
Use the Array.every() method to check if an image is not used by any user.
let availableImages = profileImages.filter(image => users.every(u => u.image != image));
The following code gets you the remaining elements without a second loop. However, programmers must be cautioned that splice() is an expensive operation and it also alters the original array:
profileImages = ['img1', 'img2', 'img3', 'img4'];
users = [
{
name: "Username1",
image: 'img1'
},
{
name: "Username2",
image: 'img2'
}
];
users.map(item => {
let i = profileImages.indexOf(item.image); // get the index
profileImages.splice(i,1); // delete it
});
profileImages; // ['img3', 'img4']
something like this can work too, but this is a very simplistic approach. you may have some edge cases depending on how these images are assigned if coming from the server-side or something.
// assuming you want to keep a reference to the full list of images
const allImages = [...];
let availableImages = [...allImages];
function getImage() {
const [newImage, ...rest] = availableImages;
availableImages = rest;
return newImage;
}
// use getImage(); when you want to assign a new image