Hope I can describe this properly.
I've made a template HTML element to be filled up by info from an array when I run an onclick function. There will be different arrays so I've put them on a much bigger array. Now, what I was hoping to do, is to be able to call a random array off of the main Array then also be able to call the individual elements of the random array.
I tried creating an index randomizer and called on the arrays with it... it worked fine but you're bound to get the same set...
I've read and tried splicing, and the logic works fine. Console.logs shows that I got a random array, but when I try to pull out elements off the array I'm getting "undefined".
Here's a view of the code:
object00 = ["Cat", "Dog", "Cow", "Goat"];
object01 = ["Apple", "Banana", "Orange", "Manggo"];
.
.
.
mainArray = [object00, object01, . . .];
function next () {
if(mainArray.length == 0) return;
array = mainArray.splice(Math.floor(Math.random() *mainArray.length),1);
console.log(array); //displays [Array (4)]
console.log(array[1]); //displays undefined
}
I've read that spliced elements cannot be chained: is that the case?
Would appreciate it if anyone can explain to me what's going on and how I can work around it.
console.log(array); //displays [Array (4)]
If this happens your array must be array[0]
so to access a element you must do:
console.log(array[0][1]) //1. element
console.log(array[0][3]) //3. element
Or you can do this :
array = mainArray.splice(Math.floor(Math.random() *mainArray.length),1)[0]
Now you can access a element like this:
console.log(array[1]) //1. element
console.log(array[3]) //3. element
Your splice return a subarray. in your case is subarray with length 1, which include an array. So actually you have a 2 dimensional array. to access the target array you should first get it (array[0]).
Anyway, I think better solution will be just randomly sort the mainArray then just iterate it from index 0 to array.length-1.
to randomize array use:
mainArray = mainArray.sort((a,b) => Math.random() - .5)
live example:
var array = [1, 2, 3, 4, 5, 6, 7, 8];
var shuffled = array.sort((a,b)=> Math.random()-.5)
console.log(shuffled)
Related
myArray = [];
myArray.length;
myArray[1000000] = true;
myArray.length;
why does this return 100001?
ive read this in douglas crockford book and i dont understand what this
means
1000001, you've probably meant. An array is extended as soon as you access its element beyond current bounds. That is why after you touch its element no. 10⁶, it becomes of 10⁶ + 1 elements.
Maybe you check with a smaller index, like 10 and have a look to the values of the array.
The result is a sparse array with missing indices and one value on index 10.
The length is, as always, last index plus one.
var myArray = [];
console.log(myArray.length);
myArray[10] = true;
console.log(myArray.length);
console.log(myArray);
It returns 100001 because,
myArray = []; creates an empty array
That's why myArray.length; = 0
When you do myArray[1000000] = true;
that time actually what happens is it puts all values from 0th index to 999999th index to undefined and then puts you 1000000 value to true. so actually there are 1000001 values in an array.
That's why the length is 1000001
every function of array specifies that array works as a collection of things in a sequence which means you cant put value at random place even if you provide any random index the by the default value (undefined) will be available as a value for other places.
Arrays start at index 0, so if we have an array:
var arr = [1,2,3,4,5];
arr[0] is 1, arr[1] is 2 and so on, and the array's length is 5, because it contains 5 "elements". So, arrays start at index 0 (if you wanted to get the first element of the array, you would have to run arr[0], not arr[1], because arr[1] would be the second element) but .length counts the elements and starts with "1" for the first element, "2" for the second element, etc.
Now when you run this:
var arr = [1,2,3,4,5];
arr[200] = "whatever";
console.log(arr);
You will get this output:
(201) [1, 2, 3, 4, 5, undefined × 195, "whatever"]
So when we randomly added an element to the array at index 200 (which is actually the 201th element in the array, since arrays start at 0, not 1), the array's length just grew from 5 to 201 (the same thing can be seen in the output), and as you can see in the output, the array now contains the original 5 elements (1, 2, 3, 4 and 5), 195 ghost elements whose value undefined when you query them (don't bother what I mean by ghost element just now though), and 1 "whatever" element at its end (the output in the console would be slightly different if you manually inserted the 195 undefined elements, but don't bother yourself with such things for now).
So in your case, an array is defined (myArray), by default, it contains nothing, so it has a length of 0. Then you go on and say "I want to add an element at the 1000000th index of this array" (the line myArray[1000000] = true), don't let the true value of the added element confuse you! the output would be the same regardless of what followed the myArray[1000000] = part, so myArray[1000000] = "whatever" would give you the same output: an array whose length is 1000001. Here is the output of your array when used with console.log(..) (remember, the output would be the same even if "whatever" was inserted in place of true):
(1000001) [undefined × 1000000, true]
Also, remember, the array you get when you say var arr = []; arr[1000] = "foo" is sparse (If you are interested in sparse arrays)
The other comments have answered your question correctly as well but I decided to do so because: 1. I have a bad feeling the true part in myArray[1000000] = true is confusing you. 2. They explained the arrays-start-at-0 thing in a not-too-clear way.
Starting out with:
ArrayA = [ ["Element0"], ["Element1"], ["Element2"] ];
and
ArrayB = [];
After a for-loop:
ArrayB[i] = ArrayA.splice(x,1);
then
ArrayB = [ [["Element0"]], [["Element1"]], [["Element2"]] ]
Any clue WHY this is happening?
Array.splice returns an array of the removed items. In ArrayA, each item is an array, so Array.splice returns an array containing that array. For example,
ArrayA.splice(0, 1) returns [["Element0"]]. If you use a look to populate ArrayB like this, you'll end up with an array in which each element is an array containing a single array, which is what you have.
If you always use Array.splice for a single element and you want that element to be returned, you could write ArrayA.splice(0, 1)[0] to get the first element.
Also, do you really want ArrayA to be an array of arrays? Or do you want it to be an array of strings? If so, that would simply be ArrayA = ["Element0", "Element1", "Element2"]; and the result of ArrayA.splice(0, 1) would be "Element0".
I have this code that fetches data and puts it into an array:
this.$httpGetTest(this.test.testId)
.success(function (data: ITestQuestion[]) {
self.test.qs = data;
});
It works and populates the array starting with self.test.qs[0].
However many times my code references this array (which contains a list of questions 1...x)
I must always remember to subract 1 from the question number and so my code does not look clear. Is there a way that I could place an entry ahead of all the others in the array so that:
self.test.qs[0] is null
self.test.qs[1] references the first real data for question number 1.
Ideally I would like to do this by putting something after the self.test.qs = and before data.
Push values at start of array via unshift
self.test.qs.unshift(null);
You need to use Splice(), It works like:
The splice() method changes the content of an array, adding new elements while removing old elements.
so try:
self.test.qs.splice(0, 0, null);
Here mid argument 0 is to set no elements to remove from array so it will insert null at zero and move all other elements.
Here is demo:
var arr = [];
arr[0] = "Hello";
arr[1] = "Friend";
alert(arr.join());
arr.splice(1,0,"my");
alert(arr.join());
You can start off with an array with a null value in it, then concat the questions array to it.
var arr = [null];
arr = arr.concat(data);
You could do something like:
x = [null].concat([1, 2, 3]);
Though there isn't anything wrong with doing something like:
x[index-1]
I'd prefer it to be honest, otherwise someone might assume that the index value returned is 0 based.
Regarding this post (Remove Duplicates from JavaScript Array) on creating a new array of unique values from another array.
Code in question:
uniqueArray = myArray.filter(function(elem, pos) {
return myArray.indexOf(elem) == pos;
})
Using this as the test data:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
Desired result is an array with only unique values:
var unique_names = ["Mike","Matt","Nancy","Adam","Jenny","Carl"];
Where I'm at:
I understand that filter will run a function on each member of the array, and that elem is the element being reviewed, and that pos is its index. If something causes that function to return false, then that element will not be included in the new array. So walking through it, this happens:
Is myArray.indexOf("Mike") the same as 0? Yes, so add "Mike" to the new array.
Is myArray.indexOf("Matt") the same as 1? Yes, so add "Matt" to the new array.
Is myArray.indexOf("Nancy") the same as 2? Yes, so add "Nancy" to the new array.
[repeat for all elements. All pass.]
Basically I don't get why the 2nd Nancy would evaluate to false.
The indexof is the index of the first appearance of the element, so the second Nancy would get the index of the first Nancy, and would be filtered out.
6) Is myArray.indexOf("Nancy") the same as 5? No (it's 2, just like it step 3), so skip the duplicated "Nancy".
indexOf gives you the first occurrence of the item.
I am trying to remove a element from my array using slice, but i can't get it to work, look at this piece of code.
console.log(this.activeEffects); // Prints my array
console.log(this.activeEffects.slice(0,1)); // Remove from index 0, and remove one.
console.log(this.activeEffects); // Prints array again, this time my element should be gone
Result of this is.
So what is get from this is, at first the array is whole, as it should be. Then its prints what is sliced of the array. Finally the third should be empty? or?
function removeItemWithSlice(index) {
return [...items.slice(0, index), ...items.slice(index + 1)]
}
Slice will create a new array. We create two arrays: from beggining to index and from index+1 to end. Then we apply the spread operator (...) to take the items of those arrays and create a new single array containing all the items we care. I will paste an equivalent way if you don't like the one liner:
function removeItemWithSlice(index) {
const firstArr = items.slice(0, index);
const secondArr = items.slice(index + 1);
return [...firstArr , ...secondArr]
}
I believe you're looking for splice. From W3 Schools:
The splice() method adds/removes items to/from an array, and returns the removed item(s).
Take a look at the example on that page; the use case there is similar to what you want to achieve.
EDIT: Alternative link to MDN, as suggested by Nicosunshine; much more information about the command there.
a.slice(0, index).concat(a.slice(index + 1))
.slice does not mutate the array, you could use .splice() to remove the item at index i in the array:
this.activeEffects.splice(i, 1)
This is what I was able to come up with :
var newArray = oldArray.slice(indexOfElementToRemove+1).concat(oldArray.slice(0,indexOfElementToRemove));
Array.prototype.slice()...
does not alter the original array, but returns a new "one level
deep" copy that contains copies of the elements sliced from the
original array. Elements of the original array are copied into the new
array as follows:
Whereas Array.prototype.splice()...
Changes the content of an array, adding new elements while removing old elements.
This example should illustrate the difference.
// sample array
var list = ["a","b","c","d"];
// slice returns a new array
console.log("copied items: %o", list.slice(2));
// but leaves list itself unchanged
console.log("list: %o", list);
// splice modifies the array and returns a list of the removed items
console.log("removed items: %o", list.splice(2));
// list has changed
console.log("list: %o", list);
Look at here :
http://www.w3schools.com/jsref/jsref_slice_array.asp
You can see that the slice method select object et throw them into a new array object ^^ So you can't delete an object like this, may be you can try a thing like this :
var a = ["a","b","c"]; (pseudo code)
/* I wan't to remove the "b" object */
var result = a.slice(0,1)+a.slice(2,1); /* If you considers that "+" is a concatenation operator, i don't remember if it is true... */