0

I have a JSON array in my state and I want to use the other half of it. For example if the size of the JSON array is 10, I am interested in to access the later 5 values. How can I achieve that? I have tried many solutions but I always end up getting errors. I am working with React JS. So I was using map function but I am unable to fulfill my condition.

  data.map((item, index) => {

I am unable to use reduce or filter I tried that also.

1

2 Answers 2

2

As @SaeedShamloo mentioned slice method will be sufficient here

data.slice(Math.floor(data.length/2), data.length).map(item => )
Sign up to request clarification or add additional context in comments.

2 Comments

data.form.slice(Math.floor(0), data.form.length/2).map((item, index) => { }) Is this the right thing to do if I want to access the first half?
The op question was For example if the size of the JSON array is 10, I am interested in to access the later 5 values
1

Use filter by array indexes.

const data = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

const res = data.filter((_, idx, arr) => idx >= arr.length / 2);

console.log(res);


// Alternatively
const res2 = data.slice(-data.length/2);

console.log(res2);

Comments

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.