Anonymous
Anonymous

Reputation: 77

(JS) How to get random value from array (not length, because of keys...!)

I'm trying to get a random value of an array. The classic system is this:

tmpArray[Math.floor(Math.random()*tmpArray.length)];

But my array is not like this :

Array[0, 1, 2, 3, 4]; //length 5

But like this !

Array[123, 444, 1234, 10000, 12345]; //length 12346

I want to get a random value from it, but a random one which exists.

Any idea? (Pure JS or jQuery only)

;)

Upvotes: 2

Views: 81

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

With sparse arrays, you could filter existent items and then take a random value out of it.

var array = [1, , , , 2, , , , , , 3, , , , , , , 4, , , , 5, , , , , 6, , , , , , 7],
    temp = array.filter(_ => true);

console.log(temp);
console.log(temp[Math.floor(Math.random() * temp.length)]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Mapping all nonsparsed indices

var array = [1, , , , 2, , , , , , 3, , , , , , , 4, , , , 5, , , , , 6, , , , , , 7],
    indices = array
        .map((_, i) => i)   // map indices, got sparse array
        .filter(_ => true); // filter sparse items

console.log(indices);
console.log(array[indices[Math.floor(Math.random() * indices.length)]]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can store the indexes of elements of array which are not undefined in an array, use same procedure to get element of indexes array to set at bracket notation

let indexes = [123, 444, 1234, 10000, 12345];

let index = indexes[Math.floor(Math.random() * indexes.length)];

let res = tmpArray[index];

Upvotes: 1

pegla
pegla

Reputation: 1866

Try this:

var tmpArray = new Array(123, 444, 1234, 10000, 12345);

and after that this will work:

tmpArray[Math.floor(Math.random()*tmpArray.length)];

To explain bit better what's happening here, you're probably setting variable to array on key 123 which is in fact 123th position in array:

tmpArray[123] = {somekey: 'someval'};

then tmpArray.length would be 124 (count in 0)

There's one nice solution if you're creating array dynamically use push on array to push object to array if you need that key you can use:

tmpArray.push({number: 123, somekey: 'someval'})
tmpArray.push({number: 1234, somekey: 'someval2'})

then you can easily find what you need like this:

tmpArray.find(x=>x.number===123) //this will fetch wanted object

Upvotes: 0

Related Questions