Home > Software engineering >  JSON array splitting React JS
JSON array splitting React JS

Time:12-23

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.

CodePudding user response:

As @SaeedShamloo mentioned slice method will be sufficient here

data.slice(Math.floor(data.length/2), data.length).map(item => )

CodePudding user response:

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);

  • Related