Reputation: 263
I have a variable of array like this:
dateArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
Now I wanted to remove the first 12 elements of the dateArray
. I tried the code below but it's not working still. I used splice
but I don't know what I'm missing.
if(dateArray.length>12){
for(var d= 0; d <12; d++){
dateArray.splice(d);
}
console.log(dateArray);
}
It outputs empty array: []
what I wanted it to remove only the first 12 and the output should be:
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Any help would be much appreciated.
Upvotes: 0
Views: 272
Reputation: 23208
dateArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
dateArray.splice(0,12);
document.body.innerHTML = JSON.stringify(dateArray);
Upvotes: 3
Reputation: 462
If you want to remove the 12 elements at one time, you're not using splice()
the correct way, here the correct way to use it:
console.log(dateArraysplice(0, 12););
If you want to remove the first element of an array at a time, use the shift()
method instead.
if(dateArray.length>12){
for(var d= 0; d <12; d++){
dateArray.shift();
}
console.log(dateArray);
}
Both method get you this output
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Upvotes: 0
Reputation: 1
Try datearray.splice(0, 12)
. 0 = starting index, 12 = number of elements to remove.
ref: splice()
Good luck!
Upvotes: 0
Reputation: 1
Try, this code
if(dateArray.length>12){
dateArray.splice(0, 12);
console.log(dateArray);
}
source - https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Upvotes: 0
Reputation: 4358
You can use slice
function to remove array elements.
slice(): The slice()
method returns a shallow copy of a portion of an array into a new array object.
var d2 = dateArray.slice(12, dateArray.length);
console.log(d2); // [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Upvotes: 0
Reputation: 3336
You could also just make a new array with the values you want.
dateArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
dateArray2 = [];
if(dateArray.length>12){
for(var i= 0; i < 12; i++){
dateArray2[i] = dateArray[i];
}
console.log(dateArray);
console.log(dateArray2);
}
Jsfiddle example.
Upvotes: 0
Reputation: 10849
You don't need a for loop to do this
for(var d= 0; d <12; d++){
dateArray.splice(d);
}
Could be
dateArray.splice(0, 12);
Upvotes: 5