Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing value from array on specific location [duplicate]

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.

like image 334
GdeBrock Avatar asked Jun 15 '13 16:06

GdeBrock


People also ask

How do I remove a repeated value from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.


1 Answers

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

like image 184
outcoldman Avatar answered Sep 28 '22 16:09

outcoldman