Removing value from array on specific location

JavascriptArraysRandom

Javascript Problem Overview


I realise there is a lot of topics on this subject but I believe this one is different:

The goal is to get an value from an array on a random location then delete this value.

I use this part by John Resig (the creator of jQuery) to remove an element but it doesn't seem to listen to the location I give it

Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};

this is how I use it

var elements = ['#1','#2','#3','#4']
var R1 = Math.floor(Math.random() * elements.length),
E1 = elements.slice(R1,1)
elements.remove(R1)
var R2 = Math.floor(Math.random() * elements.length),
E2 = elements.slice(R2,1)
elements.remove(R2)
var R3 = Math.floor(Math.random() * elements.length),
E3 = elements.slice(R3,1)
elements.remove(R3)
var R4 = Math.floor(Math.random() * elements.length),
E4 = elements.slice(R4,1)

The problem is the remove function, it doesn't work when removing a object on a specific location I believe.

Javascript Solutions


Solution 1 - Javascript

You are using elements.slice(R3,1) wrong. Second argument means not the length of the array you want to get, but the zero-based index of the element when slice method should stop. So your code is saying "Give me elements from index R3 till index 1", and the only one time when it will work: elements.slice(0, 1). If you just need to get one element - use elements[R1]. If you need to get array with one element you can keep using slice with elements.slice(R1, R1 + 1);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGdeBrockView Question on Stackoverflow
Solution 1 - JavascriptoutcoldmanView Answer on Stackoverflow