I have a function that takes an array, consisting of 3 sets of strings. For each set of strings, the function should spit out 2 resulting integers/numbers.
Link to the jsfiddle of work in progress
So if the input is
["10:00AM-12:30PM","02:00PM-02:45PM","09:10AM-09:50AM"]
I'm trying to get the function, by using a for-loop, to spit out 2 minute counts for each element of the array (a total of 6 minute counts, 2 per string).
I'm thinking I need the results stored in an object? Or maybe an array, consisting of objects? I'm a little bit confused here.
I'm confused as to how to organize it so that whatever is returned from the function, I can easily access it.
So maybe an array of 3 objects is returned is the best way to do it, with each object consisting of:
1st identifier key: an identifier of some sort (perhaps using the [i] from the for loop),
2nd key/property time1min: with the value being time1min (which is the 1st minute count),
3rd property time2min: with the value being time2min for that string.
As you can see from my jsfiddle above, I'm lost as to how to output to an object, or to an array of objects.
results is an array; so results[0].time1min
Try using console.log(results); instead. It plays nicer than alerts.
Related
Lets say I have these two pieces of code - which are identical. Also lets assume that the '.selector' returns atleast 2 objects.
Snippet 1
$('.selector').myMethod();
Snippet 2
$('.selector').each(function(){
$(this).myMethod();
});
Lets say for each one of the 'selected' returned objects I want to pass in the objects id wrapped up to myMethod().
So Snippet 2 could become
$('.selector').each(function(){
$(this).myMethod({attribute: $(this).attr('id')});
});
How can I do something similar with Snippet 1 (i.e without using $.each())?
For obvious reasons this isn't correct
$('.selector').myMethod({attribute: $(this).attr('id')});
as $(this) does not represent any one of the 'selected' returned object.
EDIT: In Snippet 1 Is there any way to reference the returned object as jQuery itself 'loops' through each returned object and calls the method. (again w/o $.each()).
The two pieces of code are not identical. One is a collection of objects and the other is a loop through a collection of objects. You can take an action on a collection that affect all equally or you can act individually on each object in the collection. Once you invoke the each() function you are individualizing objects in the collection.
To answer your question, there is no way to reference the returned collection of objects as if you were looping and applying a different function, calculation or result to each individual item in the collection.
This question already has an answer here:
Mutate JavaScript Array Inside Function
(1 answer)
Closed 8 years ago.
So it could just be I'm crazy tired but I can't seem to figure this out.
I've been picking up javascript which I'm finding horrible coming from actionscript 3 where everything was typed. I had a function that referenced two array variables directly, I later needed to use it again for a different data set so I've altered it to take parameters and now it's breaking.
I have one array full of elements, the 2nd is empty. When I call the function, a random element is removed from the first array and pushed into the 2nd array, that element is also returned by the function. If the 1st array is empty I have concat the 2nd array to fill it back up. The goal was to randomly iterate through the elements and not have the selected elements show up again until I had finished a full cycle.
Prior to concat I was using slice(which should work just as well?), the problem I believe is that I know have a parameter that is redefined when I do 'array = array2.slice()', concat doesn't seem to work around that. I don't know if returning the single sliced element from the first array is bad if I'm expecting a string, I think slice is returning an array with the single element, easy fix there though by adding [0] to the return statement.
Heres the code:
//Gets a random element from array, that element is moved from the 'src' array to the 'bin' array,
//this allows random selection without choosing the same element until all of 'src' array elements have been picked
function getRandomElement(array_src,array_bin){
//Randomly selects a tweet from the que, then stores it in another array so each tweet shows once before recycling
if(array_src.length==0 && array_bin.length>0) {array_src.concat(array_bin);} //Recycles array elements when the src array is empty
var randomElement = array_src.splice(Math.floor(Math.random()*array_src.length),1); //Grab a random array element
array_bin.push(randomElement);//array elements stored here to be recycled
return randomElement;
}
I think I could maybe use an object with two properties pointing to the arrays and pass those in, though it'd be nicer if there is a better way. I could also use push on array_src looping through the array_bin to work around that issue if there isn't any other way.
I wouldn't say this is a duplicate Felix. The answer you provided is pretty much the same, but the question itself is phrased differently, I wasn't aware of the term mutate, finding the question/answer wouldn't be easy, none of the suggested links SO provided were relevant. Worth keeping up for making the answer more discoverable to those unaware of the mutate term.
I have a hard time understanding the problem, but I think you are wondering why array_src.concat(array_bin) doesn't seem to do anything?
That's because .concat returns a new array. If you want to mutate the existing array_src array, you can use .push:
array_src.push.apply(array_src, array_bin);
FWIW, this has nothing to do with strong typing. JavaScript (and I guess ActionScript as well), is pass-by-value. That implies that assigning a new value to array_src doesn't change the value of the variable that was passed to getRandomElement.
But since arrays are mutable in JavaScript (and ActionScript I assume), you can mutate the array itself.
ive got a problem getting parameters from a json chain, the json I got looks something like this
[{"aa":"bb","ccc":"ddd","eeee":"ffff","ggggg":"hhhhh","iiiiii":"jjjjjj","kkkkkkk":"lllllll"}]
Im trying to count how many pairs there are inside the '{}' but i dont know how. I tried json.length and json[0].length, the first one gave me back the value '1' and the second one undefined.
Your json object is an array containing one object. So the length is 1. The object in the array has multiple properties (key/value pairs).
So in most modern browsers (except IE), this would work for you:
Object.keys(json[0]).length
Check out the answers here of various techniques for iterating/counting properties of an object in JavaScript:
How to efficiently count the number of keys/properties of an object in JavaScript?
ok i do have this literal array declared as seen in a firebug screenshot below
now i tried to traverse it by using jquery.each();
this my code
$.each(window.feeditems,function(key,val){
alert('pass OK');
console.log('index:' + key + ', ' + 'value:' + val);
});
console.log('overview:' + window.feeditems);
console.log('length:' + window.feeditems.length);
ok so with the code above, the TODO inside the callback of $.each doesn't execute as expected the length is undefined when its printed it on the console.
well in a very strange case as i printed the window.feeditems in the firebug it displays my literal array completely like what displayed in the screenshot above.
now my question is how i can traverse this kind of array? i know jquery.each() relies on the length property of the array, and im also thinking of using for loop but how i can loop without knowing its size?
UPDATE 1
i recheck again the length and transfer it somewhere, it returns length zero, but put it with the next line the content checker code, it still contains the contents of the array.
UPDATE 2
Any possible workaround so I can traverse this array on the runtime without accessing the nodes manually in the code? for example using a for loop?
An array only accepts numeric indices. You appear to be defining string keys instead, which will not count as part of the .length or show up in a .each().
Instead of starting your definition with [], use {} to allow string keys. However, keep in mind that you still won't be able to use .length.
use JavaScript For...In Statement
http://www.w3schools.com/js/js_loop_for_in.asp
http://www.w3schools.com/js/tryit.asp?filename=tryjs_object_for_in
I have two DIV-elements, which are assigned an array called "stack" using data().
Both DIV-elements have a class of .trigger.
I now want to pop() the last element of both arrays like so:
$('.trigger').data("stack").pop()
However this only takes off the last element of the FIRST array, although
$('trigger').length
Returns 2.
Is there a way to remove the last element from both arrays in a single line?
You could do this:
$('.trigger').each(function() { $(this).data('stack').pop(); });
In general, jQuery functions that return a value (like ".data()" or ".css()" when passed just 1 string argument) only operate on the first element in the matched array. Thus when you want to do something like your deal, you use an explicit ".each()" to get at each element yourself.
You could use 'map' -
var arr = $('.trigger').map(function() {
return $(this).data("stack").pop()
})
Demo - http://jsfiddle.net/5gvAH/
As Pointy points out this solution works well if you need the values that were popped from each array. If you just want to pop off the values and don't need the returned values then Pointy's suggestion would be the best fit.