JavaScript Array: Get "Range" of Items

JavaScript Array: get range of items

Use the array.slice(begin [, end]) function.

var a = ['a','b','c','d','e','f','g'];
var sliced = a.slice(0, 3); //will contain ['a', 'b', 'c']

The last index is non-inclusive; to mimic ruby's behavior you have to increment the end value. So I guess slice behaves more like a[m...n] in ruby.

return an index range of elements in an array

You can use slice

var array = ["1", "2", "3"]
let indexRange = (arr, start, end) => { return arr.slice(start, end)}console.log(indexRange(array, 0, 3));

Does JavaScript have a method like range() to generate a range within the supplied bounds?

It works for characters and numbers, going forwards or backwards with an optional step.

var range = function(start, end, step) {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;

if (step === 0) {
throw TypeError("Step cannot be zero.");
}

if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}

typeof step == "undefined" && (step = 1);

if (end < start) {
step = -step;
}

if (typeofStart == "number") {

while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}

} else if (typeofStart == "string") {

if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}

start = start.charCodeAt(0);
end = end.charCodeAt(0);

while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}

} else {
throw TypeError("Only string and number types are supported");
}

return range;

}

jsFiddle.

If augmenting native types is your thing, then assign it to Array.range.

var range = function(start, end, step) {    var range = [];    var typeofStart = typeof start;    var typeofEnd = typeof end;
if (step === 0) { throw TypeError("Step cannot be zero."); }
if (typeofStart == "undefined" || typeofEnd == "undefined") { throw TypeError("Must pass start and end arguments."); } else if (typeofStart != typeofEnd) { throw TypeError("Start and end arguments must be of same type."); }
typeof step == "undefined" && (step = 1);
if (end < start) { step = -step; }
if (typeofStart == "number") {
while (step > 0 ? end >= start : end <= start) { range.push(start); start += step; }
} else if (typeofStart == "string") {
if (start.length != 1 || end.length != 1) { throw TypeError("Only strings with one character are supported."); }
start = start.charCodeAt(0); end = end.charCodeAt(0);
while (step > 0 ? end >= start : end <= start) { range.push(String.fromCharCode(start)); start += step; }
} else { throw TypeError("Only string and number types are supported"); }
return range;
}
console.log(range("A", "Z", 1));console.log(range("Z", "A", 1));console.log(range("A", "Z", 3));

console.log(range(0, 25, 1));
console.log(range(0, 25, 5));console.log(range(20, 5, 5));

How to get 'range' of items in descending order?

Use .reverse:

var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 4 }];
myArray = myArray.slice(2,4).reverse();
console.log(myArray);

Get range of numbers from the sorted array

This is a perfect use-case of for...of loop.

const array = [100, 400, 700, 1000, 1300, 1600];

function foobar(array,min,max) {
let new_array = [];
for (let val of array) {
if(min<=val && val<=max) {
new_array.push(val);
} else if(val>max) {
new_array.push(val);
break;
}

}
return new_array;
}

console.log(foobar(array,0,15)); // outputs [100]
console.log(foobar(array,250,1010)); // outputs [400, 700, 1000, 1300]

It's simple, follows conventional programming paradigm and it traverses the array only once.

How to return a specific range of indexes from within in a JSON Array?

If you can use ES2019+:

const getPastCasesByCountry = (response, country, pastDays) => Object.fromEntries(
Object.entries(response[country].dates)
.sort(([date1], [date2]) => date1.localeCompare(date2))
.slice(-pastDays)
);

const last7DaysAN = getPastCasesByCountry(response, 'AN', 7);

This uses

  • the handy Object.entries + Object.fromEntries combo which gives you the ability to work with an object essentialy the same way as with an array
  • the fact that Array.slice can take a negative start index, which is an offset from the end – as we needed here

Convert to data set

To convert to DataSet as described in your question, I'd change the function a bit:

const getPastCasesByCountry = (response, country, pastDays) => 
Object.entries(response[country].dates)
.sort(([date1], [date2]) => date1.localeCompare(date2))
.slice(-pastDays)

const DataSet = (casesByDate) => casesByDate.map(([dateString, cases]) => ({
x: new Date(dateString),
y: cases.total.confirmed
}))

const data = DataSet(getPastCasesByCountry(response, 'AN', 7));


Related Topics



Leave a reply



Submit