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?

1
  • 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 Commented May 1, 2019 at 13:44

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.