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

117
Visualizações
Create an array based on another array with less elements

I have the following array with hundreds of objects

const images = [
  {
    "name" : "sky",
    "width" : "90",
    "height" : "150",
    "colours" : ["pink", "yellow", "red"],
    "price": "64"
  },
  {
    "name" : "old car",
    "width" : "90",
    "height" : "150",
    "colours" : ["dark purple", "sand", "light green"],
    "price": "35"
  },
  {
    "name" : "landscape",
    "width" : "90",
    "height" : "150",
    "colours" : ["dark blue", "violet"],
    "price": "85"
  },
  {
    "name" : "kitchen",
    "width" : "90",
    "height" : "150",
    "colours" : ["red", "green"],
    "price": "38"
  },
...
]

I want to create a new array that has only 10 objects and only some key/value pairs (name, colours, price). The 10 objects can be extracted by using another array of numbers to be used as index.

Here is an example of array containing the indices:

randomNum = [4,24,39,82,92,27,123,22,84,65]

The new array - expected result - should look like something similar to this

data = [
  {
      name: "landscape",
      colour: ["dark blue", "violet"],
      price: "85"
  },
  {
      name: "kitchen",
      colour: ["red", "green"],
      price: "38"
  },
  ...
]

I'm trying to iterate

const finalList = []; //new array
let quizItem;

for (let i = 0; i < 10; i++) { 
   quizItem= images[randomNum[i]];
   finalList.push({name: quizItem.name, colour: quizItem.colour, price: quizItem.price);  
}

I get an error saying... undefined is not an object (evaluating 'quizItem.name')

If instead I just use quizList.push(quizItem); it works fine and creates a new array with just the 10 records but with all the same object's items (key/value pairs) as the original array.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The issue you are facing here is when you are accessing randomNum[i], the values you are getting with randomNum[i] are probably out of bounds of the images list. Hence you're attempting to access something that is not there or simply undefined. As a solution, you can generate a random list safely as shown below and then use that to print your items.

    const images = [
    {
        "name": "sky",
        "width": "90",
        "height": "150",
        "colours": ["pink", "yellow", "red"],
        "price": "64"
    },
    {
        "name": "old car",
        "width": "90",
        "height": "150",
        "colours": ["dark purple", "sand", "light green"],
        "price": "35"
    },
    {
        "name": "landscape",
        "width": "90",
        "height": "150",
        "colours": ["dark blue", "violet"],
        "price": "85"
    },
    {
        "name": "kitchen",
        "width": "90",
        "height": "150",
        "colours": ["red", "green"],
        "price": "38"
    }
];

    generateRandomNumbersList = (size, maxValue) => {
    let randomNums = [];
    let currentNum;

    while (randomNums.length < size) {
        currentNum = Math.floor(Math.random() * maxValue);
        if (currentNum < maxValue) {
            randomNums.push(currentNum);
        }
    }
    return randomNums;
}

    let randomNums = generateRandomNumbersList(10, images.length);

    const finalList = []; //new array
    let quizItem;

    for (let count = 0; count < 10; count++) {
    quizItem = images[randomNums[count]];
    finalList.push({ name: quizItem.name, colour: quizItem.colours, price: quizItem.price });
}

    console.log(finalList);
about 4 years ago · Juan Pablo Isaza Relatório

0

Your code should work fine with the correction pointed out in the comments. Also, you do not have a colour property in the objects; but you have colours; correct that too. You can also use .map() as follows:

const finalList = randomNum.map(n => images[n])
.map(({name, colours, price}) => ({name, colours, price});
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