let assume I have array
arr=[1,2,3,4,5,6,7,8,9,10]
so I want iterate based on two value one is index, and offset
, for example, index=2
, offet=5
expected output
newArray=[3,4,5,6,7]
I tried .slice but it is not meet the requirement
let assume I have array
arr=[1,2,3,4,5,6,7,8,9,10]
so I want iterate based on two value one is index, and offset
, for example, index=2
, offet=5
expected output
newArray=[3,4,5,6,7]
I tried .slice but it is not meet the requirement
console.log([1,2,3,4,5,6,7,8,9,10].splice(2,5))
You need for Array#slice
as second parameter an index, not the length of the part. Just add the index as well.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
index = 2,
offset = 5,
result = array.slice(index, index + offset);
console.log(result);
Using slice()
arr.slice([begin[, end]])
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let index = 2, offset = 5
console.log(arr.slice(index, index + offset))
Using splice()
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let index = 2, offset = 5
console.log(Array.from(arr).splice(index, offset))
slice() should meet your requirements:
Array.prototype.slice(index, index + offset);
You can slice()
like this and then iterate the result using the standard map()
method of Array
let arr = [1,2,3,4,5,6,7,8,9];
arr.slice(2, 6).map((element, index)=>console.log(element, index));