Home > Software engineering >  Create an array based on another array with less elements
Create an array based on another array with less elements

Time:11-25

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.

CodePudding user response:

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);

CodePudding user response:

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});
  • Related