Reputation: 419
I have an array of objects that I'm attempting to slice at a different index depending on the URL.
data.Results.Data
is my array.
I declared a variable arrList
to equal data.Results.Data
when console.logging my arrList
I see the results I am expecting.
When starting my condition and slicing at different indexes and then console.logging the array I am getting back the entire array not the sliced array I am expecting.
Here is my code:
function retrieveData(data) {
const arrList = data.Results.Data;
const urlStr = window.location.pathname;
if (urlStr.includes("/states/")) {
arrList.slice(23, 46);
console.log(arrList, "Slice");
} else if (urlStr.includes("/countries/")) {
arrList.slice(46, 69);
console.log(arrList, "Slice");
} else if (urlStr.includes("/cities/")) {
arrList.slice(69, 90);
console.log(arrList, "Slice");
}
}
I've tried declaring arrList
inside of the condition statement which works, but I would like the variable arrList
available throughout the entire scope of the function. I am expecting to see the sliced array when the condition is met.
Upvotes: 0
Views: 468
Reputation: 8125
slice does not replace or modify the existing array.. You need to redefine it
arrList = arrList.slice(69, 90)
Else use splice.
function retrieveData(data) {
const arrList = data.Results.Data;
const urlStr = window.location.pathname;
let slicedData = [];
if (urlStr.includes("/states/")) {
slicedData = arrList.slice(23, 46);
console.log(arrList, "Slice");
} else if (urlStr.includes("/countries/")) {
slicedData = arrList.slice(46, 69);
console.log(arrList, "Slice");
} else if (urlStr.includes("/cities/")) {
slicedData = arrList.slice(69, 90);
console.log(arrList, "Slice");
}
return slicedData;
}
Upvotes: 1