0

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

Tien Duong
  • 2,517
  • 1
  • 10
  • 27

5 Answers5

2

console.log([1,2,3,4,5,6,7,8,9,10].splice(2,5))
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
  • 2
    this approach mutates the array. this is not a side effect, but the real purpose of [`Array#splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). – Nina Scholz Jul 25 '19 at 07:21
2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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))
User863
  • 19,346
  • 2
  • 17
  • 41
0

slice() should meet your requirements:

Array.prototype.slice(index, index + offset);
Almog Gabay
  • 135
  • 7
0

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));
Harsh kurra
  • 1,094
  • 1
  • 9
  • 19