0

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.

3
  • 1
    is it typo or on purpose ?? arrList.Slice slice on caps Commented Apr 29, 2020 at 14:16
  • sorry it is not, should be arrList.slice. Has been edited Commented Apr 29, 2020 at 14:16
  • you can create a new variable and assign the original array to it then slice like that: arr = arr.slice(beginning,end); and to deep copy an object so you really keep the original intact you can do like that: arr = JSON.parse(JSON.stringify(arrList)) Commented Apr 29, 2020 at 14:19

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry, I'm confused about the redinfe part. I am trying to access the sliced array outside of the condition. if I am re-defining arrList = arrList.slice am I leaving the arrList = data.Results.Data variable at the start of the function?
yes u can do that. create a variable. I have update my answer check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.