Home > database >  React.JS Storing mapped API repsonse into a new array based on matching values
React.JS Storing mapped API repsonse into a new array based on matching values

Time:03-03

Using React, I have data from an API response. I mapped the data and am storing the visitID, which would be the main identifier, into a variable. What I would like to do is look for any matching visitID values and store them into a new array, the issue I'm having is each instance is being stored in it's own array, for example:

['7065682'] at Index 0

['7065682'] at Index 1

['7065682'] at Index 2

['7047674'] at Index 3

['7047674'] at Index 4

I would like to look through each iteration and check all, put matching values into it's own array so I can write some logic based off each unique value. I just don't understand how to look through the next iteration. Here's my code, and the function 'duplicateVisitID' that I've been trying, but it doesn't give me the results I'm looking for.

      {
        Object.keys(this.state.EncounterData).length !== 0 ?
          Object.values(this.state.EncounterData).map((encounter, i) => {
            

            const visitID = [encounter.resource.identifier[1].value];

            console.log(visitID, i);

            const duplicateVisitID = function (visitID) {
              if (visitID[i] === visitID[i])
              return [visitID.concat(visitID[i])]
            } 

CodePudding user response:

I am not sure what do you want to do, but if I understood right you want new array with only strings that are unique, not repeating. If yes see the code below. This is not the best performing one because of iteration inside iteration, but it will work for you. You can optimize it later by applying some algorithms.

The newArr is equal to ['7065682', '7047674']

const EncounteredData = [['7065682'], ['7065682'], ['7065682'], ['7047674'], ['7047674']];

const newArr = [];

for(let i of EncounteredData) {
    for(let j of EncounteredData) {
        if((i[0] !== j[0]) && !newArr.includes(i[0])) newArr.push(i[0]);
    }
}

console.log(newArr);

CodePudding user response:

If I understand correctly, you want an array of unique values? If so then you can use the map function and add any unique values to an array if the value is not already in it:

const uniqueVals = [];

EncounteredData.map((visitID) => {
  if (!uniqueVals.includes(visitID[0])) {
    uniqueVals.push(visitID[0]);
  }
});
  • Related