JavaScript/jQuery: array random issue [duplicate] - javascript

This question already has answers here:
jQuery - Access elements in array
(3 answers)
Closed 5 years ago.
I'm trying to randomize an array with DOM elements, like this:
var allTargets=$('#target1, #target2, #target3, #target4');
var randomTargets=null;
randomTargets = allTargets[Math.floor(Math.random() * allTargets.length)];
console.log(randomTargets);
In the console I can see the array is shuffled each time I refresh the page. But when I try to trigger a method with the randomTargets variable, the program crashes. Something like this:
randomTargets.hide();
But without the random variable, the program works:
var allTargets=$('#target1, #target2, #target3, #target4');
allTargets.hide();
What am I doing wrong?

Perhaps you meant this which will not shuffle but just hide a random element based on a random number from 0 to length of allTargets
var $allTargets = $('#target1, #target2, #target3, #target4');
var rnd = Math.floor(Math.random() * allTargets.length);
$allTargets.eq(rnd).hide();

Accessing a jQuery object "like an array" gives you a native DOM element which has no hide() method.
From the docs at https://api.jquery.com/get/
Each jQuery object also masquerades as an array, so we can use the
array dereferencing operator to get at the list item instead:
console.log( $( "li" )[ 0 ] );
So in your case $(randomTargets).hide(); will work.

Related

Finding last occurences of element in Array of Array with lastIndexOf [duplicate]

This question already has answers here:
Find last index of element inside array by certain condition
(23 answers)
Closed 2 years ago.
Is it possible somehow to use the lastIndexOf method to get the value of a variable in an array of array? For example if I had
[[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]]
and I wanted to find the index of the last array where [1] was 2? In the above I would expect the answer to be 3 as the third array has [1] equal to 2.
I can see how I can make this work with nested loops or array methods but just wondered if there's some syntax I'm not aware of. Cheers
No.
Because Array.prototype.lastIndexOf() only accepts an element, and not a callback, you can't use lastIndexOf() for this case directly.
Given this, and that there's no standard findLastIndex() prototype function, you'll have to write this functionality yourself. Here's one such way, using reduce() and findIndex(), while avoiding mutating the original array:
const arr = [[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]];
function findLastIndex(arr, callback) {
return (arr.length - 1) - // Need to subtract found, backwards index from length
arr.slice().reverse() // Get reversed copy of array
.findIndex(callback); // Find element satisfying callback in rev. array
}
console.log(findLastIndex(arr, (e) => e[1] == 2));
I discovered arr.slice().reverse() from this answer by user #Rajesh, which is much faster than my previous reducer.

How to get last item in array Node.js? [duplicate]

This question already has answers here:
Get the last item in an array
(59 answers)
Closed 5 years ago.
I am new to node.js and JavaScript so this question might be quite simple but I cannot figure it out.
I have a lot of items in an array but only want to get the last item. I tried to use lodash but it somehow does not provide me with the last item in the array.
My array looks like this now:
images : ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', ..., 'jpg.item_n']
and i want to get:
images : 'jpg.item_n'
Using lodash I am getting:
images : ['g.item_1', 'g.item_2', 'g.item_n']
It looks like I am just getting the last letter in jpg, i.e. 'g'.
My code using lodash looks like this:
const _ = require('lodash');
return getEvents().then(rawEvents => {
const eventsToBeInserted = rawEvents.map(event => {
return {
images: !!event.images ? event.images.map(image => _.last(image.url)) : []
}
})
})
Your problem is that you're using _.last inside map. This will get the last character in the current item. You want to get the last element of the actual Array.
You can do this with pop(), however it should be noted that it is destructive (will remove the last item from the array).
Non-destructive vanilla solution:
var arr = ['thing1', 'thing2'];
console.log(arr[arr.length-1]); // 'thing2'
Or, with lodash:
_.last(event.images);
Use .pop() array method
var images = ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];
var index= images.length - 1; //Last index of array
console.log(images[index]);
//or,
console.log(images.pop())// it will remove the last item from array
Although Array.prototype.pop retrieves the last element of the array it also removes this element from the array. So one should combine Array.prototype.pop with Array.prototype.slice:
var images = ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];
console.log(images.slice(-1).pop());

calling an object using variable [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
I have several javascript sliders on a page and I want to be able to enable or disable each by using a variable.
For example, I have a slider:
var slider1 = new Slider('#sitSlider', {
formatter: function(value) {
return value;} });
and I enable/disable it with this:
slider1.disable();
I would like to be able to do something like this to turn off several switches:
for(x=0;x<20;x++){
var tmpStr = "slider"+x;
tmpStr.disable();
}
I did some searching and tried this without success:
this[tmpStr].disable();
How do I go about using a variable to call an object? Thanks.
Edit: Here's the slider component I'm using: Bootstrap Slider
Create an array:
var sliders = [];
Push your objects onto that array:
sliders.push(new Slider(...));
Then in your loop you can access the array elements:
for(x = 0; x < sliders.length; x++){
sliders[x].disable; // side note: missing parentheses here?
}
Any time you're trying to use an incrementing number as part of a variable name, you're probably looking for an array or collection of some kind.
No. You cannot do that. Variable name shouldn't be given like that.
The easiest you can do create an array and push your sliders. And you can loop the array and access the sliders.
var sldsr =[];
...
sldsr.push(slider1);
...
sldsr.push(slider2);
for(x=0;x<sldsr.length;x++){
sldsr[x].disable();
}

Swapping elements in an array of objects [duplicate]

This question already has answers here:
Javascript swap array elements
(33 answers)
Closed 9 years ago.
I have an array of objects and I want to swap the position of two elements in the array.
I tried this:
var tempObject = array.splice(index, 1, array[index + 1]);
array.splice(index+1, 1, tempObject);
But it doesn't seem to work properly as it results in some weird errors. For example, I am unable to use methods of the object. Calling array[x].getName results in an error.
Can any body lend a helping hand here?
Just in case it is important, I have used object.prototype to add the methods.
The bug in your code is that splice returns an array of items, not a single item. Since you are extracting a single item, you could do:
var tempObject = array.splice(index, 1, array[index + 1])[0]; // get the item from the array
array.splice(index+1, 1, tempObject);
This answer provides a shorter version, also using splice:
array[index] = array.splice(index+1, 1, array[index])[0];
Another very interesting answer is both short and fast:
function identity(x){return x};
array[index] = identity(array[index+1], array[index+1]=array[index]);
JSFIDDLE
var array_of_numbers = [5,4,3,2,1,0],
swap = function(array,a,b){var tmp=array[a];array[a]=array[b];array[b]=tmp;};
swap(array_of_numbers,0,4);
// array_of_numbers now is [1,4,3,2,5,0]
Or you can do add the function to the Array.prototype:
JSFIDDLE
Array.prototype.swap = function(a,b){ var tmp=this[a];this[a]=this[b];this[b]=tmp;};
var array_of_numbers = [5,4,3,2,1,0];
array_of_numbers.swap(0,4);
// array_of_numbers now is [1,4,3,2,5,0]

Array with numbers 1-20 [duplicate]

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Closed 9 years ago.
I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.
I did this with the following:
var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
QUESTION:
I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?
Here's a oneliner:
var myArr = Array(20).join().split(',').map(function(a){return this.i++},{i:1});
or a tiny bit shorter:
var myArr = (''+Array(20)).split(',').map(function(){return this[0]++;}, [1]);
Both methods create an empty Array with 20 empty elements (i.e. elements with value undefined). On a thus created Array the map method can't be applied 1, so the join (or string addition) and split trick transforms it to an Array that knows it. Now the map callback (see the MDN link) does nothing more than sending an increment of the initial value ({i:1} or [1]) back for each element of the Array, and after that, myArr contains 20 numeric values from 1 to 20.
Addendum: ES20xx
[...Array(21).keys()].slice(1);
Array.map => See also...
See also this Stackblitz project.
1 Why not? See this SO answer, and this one for a more profound explanation
You could use a simple loop to do what you want;
var numberArray = [];
for(var i = 1; i <= 20; i++){
numberArray.push(i);
}
console.log(numberArray);

Categories

Resources