简体   繁体   中英

Slice array and concat in javascript

In case when arr = [1, 2, 3, 4] all works great.

var arr = [1, 2, 3, 4];

function range(min, max) {
    var startArr = arr.slice(arr.indexOf(min)),
        endArr = max < arr.length ? arr.slice(0, arr.indexOf(max) + 1) : [];
    return startArr.concat(endArr);
}


range(3,1);

But in case when arr = [{id:1, name: "John"}, {id:2, name: "Mark"}, {id:3, name: "Jim"},{id:4, name: "Bob"}] this code not works.

jsfiddle

Consider using the 'lodash' javascript library https://lodash.com/

For an 'array'

Sounds like you are after either

  1. Slice - http://devdocs.io/lodash/index#slice
  2. TakeWhile

This is because of the indexOf() part of your function is looking for the index based on the value. In your first array there are elements with the value 3 and 1 , but the second is an array of objects, so clearly it will not correct find them. Instead simply use the direct index given. Use the values of max,min as the index themselves. Note that the index goes from 0 .. n-1 rather than 1 .. n . So then range(3,1) would be range(2,0) ( if you want to use it as range(3,1) just subtract 1 from the values inside the function ):

function range(min, max) {
    var startArr = max >= min ? arr.slice(min, max + 1) : arr.slice(min),
        endArr = max < min ? arr.slice(0, max + 1) : [];
    return startArr.concat(endArr);
}
...
range(2, 0);

Fiddle Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM