Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

reactjs - how to create an array of unique items in an JSON response array?

I want to push the unique items in an array to an empty array from the below response which is enter image description here

Here the title key is same for many items, I want to push the unique items to an empty array for which I have written the following function which is :

const getPendingList = (data) => {
    if (data) {
      var stack = [];
      for (let i = 0; i < data.length - 1; i++) {
        if (data[i + 1].title !== data[i].title) {
          stack.push(data[i].title);
        }
      }
      console.log('stack', stack);
      return stack.length;
    }
  };

But when I console stack here, I ain't getting the last unique item : enter image description here

If I change the loop to

for (let i = 0; i < data.length; i++)

for some unknown reason am getting the following error:

enter image description here could anyone please let me know where have I gone wrong? Any leads would be great, kindly let me know if anything else is required for better understanding.

question from:https://stackoverflow.com/questions/65902340/how-to-create-an-array-of-unique-items-in-an-json-response-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue is with this piece of code

for (let i = 0; i < data.length - 1; i++) {
    if (data[i + 1].title !== data[i].title) {
      stack.push(data[i].title);
    }
  }

Change data.length - 1 to data.length.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...