Seen this question a lot, but cannot find something that's what i'm looking for.
onClick I push an item to an array I have, however, if there's 3 items in my array I don't want to be able to push items anymore.
var selectedData = [];
I set my empty variable.
var index = selectedData.indexOf(3);
I then get the index of my array which is 3
if (index > 3) {
selectedData.splice(index, 1);
}
Then within my if statement I say, if my index which is 3, is bigger then 3, then splice at index and remove one.
selectedData.push(TheThing);
I then push TheThing to my array if the if statement above isn't true.
However, I have a variable var arrayLength = selectedData.length; that grabs the length, and when I console log it, it starts at 0 and splices items anything after 4. Not 3.
Any idea what i've done wrong or misunderstood?
Thanks
More full example of my code
var selectedData = [];
myElement.on('click', function() {
var index = selectedData.indexOf(3);
if (index > 3) {
selectedData.splice(index, 1);
}
var arrayLength = selectedData.length;
console.log(arrayLength, 'the length');
});
So in short, onClick check my array and remove anything after the third that gets added into my array.
Do you want this to behave as a stack or a queue?
So your code here:
var index = selectedData.indexOf(3);
Is not grabbing the 3rd index - its grabbing the first index where it sees 3, or -1 if it doesn't. Replace your if statement with,
if (selectedData.length > 3) {
selectedData.pop() // removes last element (stack)
// or
selectedData = selectedData.slice(1) //remove first element (queue)
}
I think you need to try var arrayLength = selectedData.length -1;
You start at 0 like a normal array, but don't you start with an empty array?
Plus when you use .length, it returns the true count of the array or collection not a 0 index.
`
you can override push() method of your array like this:
var a = [];
a.push = function(){}
or like this
a.push = function (newEl){
if(this.length <3){
Array.prototype.push.call(this, newEl)
}
}
This is not complete example because push() can take many arguments and you should to handle this case too
var index = selectedData.indexOf(3); simply give you the index of the element of the array that has value 3
Example
selectedData = [ 0, 3 , 2];
alert( selectedData.indexOf( 3 ) ); // this will alert "1" that is the index of the element with value "3"
you can use this scenario
var selectedData = [];
myElement.on('click', function() {
//if selectedData length is less than 3, push items
});
This could work.
myElement.on('click', function() {
if(selectedData.length > 3){
selectedData = selectedData.splice(0, 3);
}
console.log(selectedData.length, 'the length');
});
Related
I'm in the making of a google sheets app script where I want to check if a value from one cell is in an array of values, then find what the index is so I can direct my function to that cell.
I'm at the point where I have my array in a variable called distArray, and I want to check if "id" is in that array.
Here's the code to better visualize:
function logs() {
let app = SpreadsheetApp
let dest = app.getActiveSpreadsheet().getSheetByName("Baza Danych");
let lastrow = dest.getLastRow();
let destArr = dest.getRange(2, 1, lastrow).getValues();
let id = app.getActiveSpreadsheet().getSheetByName("Zgloszenia").getRange(6, 2).getValue();
let position = destArr.indexOf(id);
Logger.log(id)
Logger.log(destArr)
Logger.log(position)
}
And here is the output I get.
My problem is that no matter what the value of "id" is, the index is either -1 or 0 meaning the value either is not in the array or is in the first cell.
Try to add .flat() at the end of the line:
let destArr = dest.getRange(2, 1, lastrow).getValues();
This way:
let destArr = dest.getRange(2, 1, lastrow).getValues().flat();
Explanation:
The method getValues() gives you a 2d array [[1],[2],[3],...].
The flat() method converts a 2d array into an ordinary flat array [1,2,3,...].
After that you will able to use array.indexOf(element) to get an index of the element in the array.
Description
Yuri's solution is a good example if you don't want to know which element of the array contains the value your looking for. But if you need to know which row of the array contains the value the following example shows how to search a 2D array.
Script
function find() {
try {
let a = [['a','b'],['c','d'],['e','f'],['g','h']];
let b = "f";
let c = a.findIndex( d => d.indexOf(b) >= 0 );
console.log("c = "+c);
}
catch(err) {
console.log(err);
}
}
7:51:23 AM Notice Execution started
7:51:24 AM Info c = 2
7:51:23 AM Notice Execution completed
Reference
Array.findIndex()
Array.indexOf()
I wanted to know how can we get every alternate object in a array. For EG -
arr = ["foo","bar","foo1","bar1"]
I Need The values -
fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]
If This Helps This Is My Intention -
I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..
Thanks In Advance
You can use the filter function to filter out even and odd index's.
arr = ["foo","bar","foo1","bar1"]
fir_alt = arr.filter((element, index) => index % 2 == 0);
sec_alt = arr.filter((element, index) => index % 2 == 1);
console.log('fir_alt', fir_alt)
console.log('sec_alt', sec_alt)
I'd use an index variable and a loop(for/next or your fav). Examine the index on each iteration of the loop, and determine if the index is odd or even(or 0), then take the appropriate action to capture the desired values.
If I know what you mean... We can be reasoned with odd and even index.
In this way:
let arr = ["foo","bar","foo1", "bar1"],
fir_alt = [],
sec_alt = [];
for (let i=0;i<arr.length;i++){
if ((i+2)%2==0) {
sec_alt.push(arr[i]);
}
else {
fir_alt.push(arr[i]);
}
}
How can I pass values from an array from one event click to another with jQuery?
Here is an example of I want to do: the first click event adds or remove values from the array if the input checkbox is selected or not. In the second click I want to loop trough all the elements of this array.
var array=[];
$( "input" ).on( "click", function() {
var $input=$(this)
if($input.is(":checked")){
array.push($(this).val()); //append check box value to array if is selected
}
else{
array.pop($(this).val()); // remove check box value to array if is not selected
}
})
$('#cmd').click(function() {
for (i of array) {
console.log(array[i]); // loop trough all elements in array
...
});
Your code looks ok except two things. First for for (i of array). Using of will return actual value as i, but you are using value as index in array[i].
If you want use index then use for (let i = 0; i < array.length; i++) instead.
You can also use Array.prototype.forEach() but you can't break out of it's loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Second thing is that .pop() doesn't support parameter. Use code below instead of .pop()
var index = array.indexOf($input.val());
if (index > -1) {
array.splice(index, 1);
}
If your event handlers are in different scope and #cmd handler can't see the array. You might use this little bit bad solution for sharing the array between scopes :)
$("input").on( "click", function() {
var array = $("#cmd").data("arr") || [];
var $input= $(this);
var value = $input.val();
if($input.is(":checked")){
array.push(value); /
} else {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
}
$("#cmd").data("arr", array);
});
$('#cmd').click(function() {
var array = $(this).data("arr") || [];
for (let value of array) {
console.log(value); // loop trough all elements in array
}
});
Is there a way to access the previous or next element while in a certain iteration of a $('.class').each() loop; Where the elements with class 'class' are not siblings?
I was able to do this by traversing through the DOM tree. But I was wondering if there is a more concrete and elegant solution.
Current code:
$('.slider-range').each(function(index){
var temp = $(this).closest('.panel').next('.panel').find('.slider-range');
//do something with temp
});
You will have to "store" the "selected" items in a variable and use the index passed to the callback like this:
var range = $('.slider-range');
range.each(function(index){
var temp = index > 0 ? range[index - 1] : null;
//do something with temp
});
I added a condition on the value of the index, to make the tempvariable null if index is 0.
Edit: Corrected with index - 1 to "select" the previous item.
In your loop, you have access to the current index within the collection of jquery objects.
$('.slider-range').each(function(index){
var temp = $(this).closest('.panel').next('.panel').find('.slider-range');
//do something with temp
});
You can use this to get any of the other items in that collection:
var items = $(".slider-range");
items.each(function(index) {
if (index > 0) {
var prev = items[index-1];
// do something with prev
}
});
I've been trying at this for hours now and I thought it would be really simple;
Using javascript I basically want to iterate through an array, get the current value of the index and then unset this value from the array. I've found splice() is supposed to work for this however I don't seem to be able to empty the array, there is always one value left on the arrary
var filtered = array("up", "down", "left");
function resetTags(){
var length = filtered.length;
for(i=0; i <= length; i++){
filtered.splice(i,1);
}
}
EDIT::
I'll try to explain in a bit more detail:
I'm basically trying to keep track of a listed of selected class values which are obtained
from when an item is clicked:
var filtered = array();
jQuery("li a").click(function () {
tag = jQuery(this).text();
addFiltered(tag);
});
function addFiltered(param){
var inArray = jQuery.inArray(param,filtered);
if(inArray > -1){
//param is in array, so we want to remove it from the filtered array
filtered.splice(index, 1);
});
}else{
//param isn't in array, so we want to add it to the array
filtered.splice(0, 0, param);
});
}
}
If you want to empty the array, set it to be an empty array directly:
filtered = [];
If you want to use the values before emptying the array, simply iterate before that without removing values and clear it when you are done.
What do you stand to gain by messing with convoluted solutions?
the array was defined incorrectly. That is why the code didn't excute
var filtered = ["up", "down", "left"];
function resetTags(){
var length = filtered.length;
for(i=0; i <= length; i++){
filtered.splice(i,1);
}
}
To remove items one by one:
var a = [1,2,3,4,5];
while (a.length > 0 ) {
a.splice(0,1);
}
http://jsfiddle.net/89hkH/
Well, you're incrementing. Have you tried decrementing?
var filtered = new Array("up", "down", "left");
function resetTags(){
var length = filtered.length;
for(i = length; i >= 0; i--){
filtered.splice(i,1);
}
}
This should make sure the final element is spliced.
I basically want to iterate through an array, get the current value
of the index and then unset this value from the array.
for(i=0; i <= length; i++){
filtered.splice(i,1);
}
I don't think you are clearly defining (or perhaps don't know), what you're trying to do.
Are you trying to write a pop(n) method such that:
var a = [1,2,3,4]
var result = pop(3, a)
result == [ 1, 2, 4]
Or are you just trying to walk an array and get the first element off every time? If so, you're doing it wrong. That's just a shift()
var filtered = ["up", "down", "left"]
for(i = 0 ; i<= filtered.length; i++)
{
alert(filtered);
filtered.shift();
alert(filtered);
}