0

I'm currently storing data as objects inside a array in the following way:

let data = [];

module.exports.init = function() {
    database.pool.query("SELECT * FROM data", (error, rows) => {
        if (error) {
            logUtil.log.error(`Loading failed: ${ error.message }`);
        }
        else {
            rows.forEach((row) => data.push({dimension: row.dimension, x: row.x, y: row.y, z: row.z}));
            logUtil.log.info(data);
        }
    });
};

data will hold the following now: [{ dimension: 2, x: -973.097, y: -133.411, z: 38.2531 }, { dimension: 3, x: -116.746, y: -48.414, z: 17.226 }, { dimension: 2, x: -946.746, y: -128.411, z: 37.786 }, { dimension: 2, x: -814.093, y: -106.724, z: 37.589 }]

Now I'm trying to receive a random object from this array storing a specific dimension parameter.

For example I want to return a random object storing the dimension: 2

I've tried to filter the array using something like:

let result = jsObjects.filter(data => {
  return data.dimension === 2
})

then return a random object from the result.

Question: How could I receive this random object in the best way?

turel
  • 13
  • 2
  • You've filtered the array down already, your question now boils down to "How to select a random item from an array", of which there are plenty of duplicates :) [Getting a random value from a JavaScript array](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) – Tyler Roper May 01 '19 at 13:44

2 Answers2

1

You can do it in two steps.

  1. Get all record which satisfy criteria like dimension === 2

    let resultArr = jsObjects.filter(data => { return data.dimension === 2 })

  2. Get random object from result.

    var randomElement = resultArr[Math.floor(Math.random() * resultArr.length)];

var arr = [{ dimension: 2, x: -973.097, y: -133.411, z: 38.2531 }, { dimension: 3, x: -116.746, y: -48.414, z: 17.226 }, { dimension: 2, x: -946.746, y: -128.411, z: 37.786 }, { dimension: 2, x: -814.093, y: -106.724, z: 37.589 }]

//Filter out with specific criteria
let resultArr = arr.filter(data => {
  return data.dimension === 2
})

//Get random element
var randomElement = resultArr[Math.floor(Math.random() * resultArr.length)];

console.log(randomElement)
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

You could use Math.random() and in the range of 0 to length of array.

let result = jsObjects.filter(data => {
  return data.dimension === 2
})
let randomObj = result[Math.floor(Math.random() * result.length)]
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73