Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Javascript - Best way to create array with unique elements from another array

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);
    }
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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));
about 4 years ago · Juan Pablo Isaza Relatório

0

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']
about 4 years ago · Juan Pablo Isaza Relatório

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda