Javascript indexOf in date array always resulting -1 - javascript

I'm facing a problem checking whether a date is in my array or not.
I refer to this article How to correctly use JavaScript indexOf in a date array
But when I use it in my project, it always results in -1.
Here's my code
for (var current = dateStart; current <= dateEnd; current.setDate(current.getDate() + 1)) {
console.log(this.leaveState.currentHoliday.map(Number).indexOf(+current));
}
I need to check whether current date is in currentHoliday array or not.

I think mapping doesn't require to loop into your array.
and -1 is somehow mean that the date does not exist in your array.
Maybe because in every loop you add a day to it before you see the actual day.
I think you could try:
var alldays = [...];
//you should eliminate these two codes
// datestart = something;
// dateend = something;
var holiday;
for(var i in alldays){
console.log(alldays.map(Number).indexOf(this.leaveState.currentHoliday));
}

Related

search if string exists in any value of array like indexOf

I have a cookie split into an array:
var cooks = document.cookie.split(';');
[dogs=bla, cats=sdfgh, cabbages=kjhgfdfg]
If I wanted to find the index of 'cats=sdfgh' I could use
cooks.indexOf('cats=sdfgh');
1
But if I wanted to search to see if the value cats has been set, how would I do that? cooks.indexOf(find('cat=')); or something to that effect?
So without knowing the value of cats, how can I tell if it exists in the cookie?
And, how can I get the index number of that cookie?
you could run a simple regular expression:
if(fun = document.cookie.match(/(^cats=|;cats=)([^;]+)/)){
console.log(fun);
}
it will give you an array where the 3rd member is your value if it matches :)
JSFIDDLE
However, if you dont have to support shitty browsers its worth taking a look at the the MDN cookie framework referenced in the comments.
You can use Array.prototype.some method to find the first matching value in array:
var cooks = document.cookie.split(';'); // ["dogs=bla", "cats=sdfgh", "cabbages=kjhgfdfg"]
var isSet = cooks.some(function(cookie) {
return cookie.indexOf('cats') == 0;
}); // => true

Javascript - delete array items by value LIKE [duplicate]

This question already has answers here:
remove all items in array that start with a particular string
(5 answers)
Closed 7 years ago.
I have this simple array
var array = ['x.89999', 'y.sisisis', 'x.585858'];
I want to remove all the items in the array starting by 'x.' so to return this array:
['y.sisisis']
How can i do this without having to loop or iterate all the entire array? (i know it's probably not possible so don't mind if not possible)
Is there some builtin / native code i can use?
Thanks
you may use array.filter()
var newArray = array.filter(function(item){
return item.indexOf('x.') !== 1;
});
there is no way to do this job without looping through the whole array.
The only case – array is sorted alphabetically. But sorting demands looping through too
Assuming that the items to be removed will always precede the other items alphabetically (ie x is before y), you can sort your array and then break the loop as soon as the non-x value has been found:
function filter(arr) {
arr.sort();
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i][0] !== 'x') {
break;
}
}
return arr.slice(i);
}
filter(arr); // logs: "Iterated to 5 of array length 9"
DEMO
Of course, as JazzCat mentions, this is no good if you only have one y value and it's right at the end of the array - you're still going to have to iterate over the whole array.
Alternate option is to use regular expression, something like this. Fix your regex according to your requirement.
var array = ['x.89999', 'y.sisisis', 'x.585858'];
var filtArr = array.filter(function(x){
return x.match("^[x].+$");
});
console.log(filtArr);
One different answer not using explicit iteration or Array.prototype.filter:
var array = ['x.89999', 'y.sisisis', 'x.585858'];
array = array.join("#").replace(/(#?x\.\w*)/g,"").replace(/^#/,"").split("#");
//["y.sisisis"]
Of course you will need to take care of the separator character.
The good point is that it works on old browsers (ie8) while Array.prototype.filter does not.

Moment: avoiding reference

I want to receive an array of moment objects, based on start / and date.
I wrote the following code in which the first start date is 27/12/2014:
_calculateDateInterval: function(date_start, date_end){
var current = date_start.startOf("day");
var arr_dates = [];
var i = 1;
while(date_end.startOf("day").diff(current, "days") > 0){
var copy_current = $.extend({}, current); //Clone the object without reference
console.log(copy_current);
arr_dates.push(copy_current);
current.add(1, "days");
//Break the loop for testing purposes
i++;
if(i == 2){
return false;
};
};
return arr_dates;
},
There is a problem though. Even when checking only on the first loop, the console gives me the following log:
This is confusing; when opening the dropdown, _d shows another day than when it is collapsed.
In order to store the right moment object, I need to remove the reference to the original (current) Moment object of which the day is increased on each loop. (In this case I need 27/12/2014, not the value including the day increase).
Any (better) suggestions?
Found it already in the docs:
All moments are mutable. If you want a clone of a moment, you can do
so explicitly or implicitly.
Calling moment() on a moment will clone it.

How to put an array into another array?

I have a chart that updates with the current bitcoin prices, however, the date and time on the x-axis is incorrect. It always starts at Dec. 31, 19:00 hours. In my console I am recieving the correct date and time, but I can't seem to get it to appear correctly on the chart. I'm pretty sure I need to stick one array into another. Any help is appreciated, thanks.
$.ajax({
url: "/chart/ajax_get_chart", // the URL of the controller action method
dataType: "json",
type: "GET",
success: function (result) {
var result = JSON.parse(result);
series = [];
for (var i = 0; i < result.length; i++) {
tempDate = Date.parse(result[i]['date']);
tempArray = [parseFloat(result[i]['price'])];
var date = new Date();
tempDate = date.toString();
series.push(tempArray);
var tempDate = tempDate.concat(tempArray);
}
If I understood correctly, for every i:
result[i]['date'] gives the date at position i
result[i]['price'] gives the price at position i
Now first of all, let's take a look at your loop:
for (var i = 0; i < result.length; i++) {
//Here you grab the date from the result array
tempDate = Date.parse(result[i]['date']);
//Here you grab the price from the result array and parse it to a float
tempArray = [parseFloat(result[i]['price'])];
//Here you grab the current date (of today)
var date = new Date();
//Here you overwrite the 'grabbed date' with the current date (of today)
tempDate = date.toString();
//Here you add the price at position i to the 'result array' called series
series.push(tempArray);
//Here you join tempArray with the tempDate
var tempDate = tempDate.concat(tempArray);
}
So what exactly goes wrong?
Well I have prepared a JsFiddle for you: http://jsfiddle.net/KzLFr/1/
Look closely at the code and what exactly 'shows up' in the alert box. You see that the value of tempDate is overwritten by the current date. Applying this info to your loop: you will see that for each iteration, you overwrite the date that you grab from the result array with the current date.
This means that the 'actual' dates (from result[i]['date']) are always overwritten, hence, if you would add all the tempDates to an array at each iteration, you will end up with an array consisting of result.length times the current date.
Another interesting point is your statement: var tempDate = tempDate.concat(tempArray);
As you can see in the second alert box in the JsFiddle, this will create an array which has two arrays after each other. But why in the world would you do this in every iteration?
Also, you never do something with your dates. You don't add them to an array or anything: you just create them and then leave them alone.
This begs the question: what exactly do you want to do?
Therefore:
NOTE: It could be that I am mistaken, but if I'm right you want to end up with an array that contains the x-axis information and the y-axis information. Because it is not clear from your question and your code how you want to accomplish this, I can only guess.
So by guessing what you want to end up with, I would rewrite your loop as follows:
var dateData = [];
var priceData = [];
for( var i = 0; i < result.length; i++ ){
dateData.push( result[i][0] );
priceData.push( result[i][1] );
}
You can see how this works here: http://jsfiddle.net/WT58s/1/
If that doesn't solve your problem, please explain with what you want to end up with (a two dimensional array or two different arrays?), so we can assist you better.
Also, often when you download information from the internet, the information is stored backwards; so starting with the current date and then going backwards in time.
Try and see if that is also the case with your data. If this is indeed the case, you can read about reversing here:
Reverse order of elements in 2-dimensional array

JavaScript - split, choose all after a given number

I have an dynamic array and I want to exclude the first part of the string, but I don't know how many objects there will be after the first part and I want to include them all in a new string.
string = "text.'''hi''','''who''' '''are''' '''you'''. I'm ken and you're barbie"
x = string.split("'''")[1]
Is there something I can do to include them all? like [1..?]
I have JQuery but don't think that would be necessary right?
shift:
Removes the first element from an array and returns that element. This method changes the length of the array.
Code:
x = theString.split("'''");
var firstElement = x.shift();
// Now x is the shifted array.
x[0];
You seem to want:
x = string.split("'''").slice(1);
This will return all elements of the array starting at index 1.

Categories