Valentin Georgiev
Valentin Georgiev

Reputation: 39

Comparing a value from two different array of objects in React.JS

I am looking for a simple solution to compare just the "session" values from two different arrays of objects using React.JS.

I have:

  this.state = {
        dataOne: [
            {
                id: "1",
                session: "10:00",
                value: "10:00"
            },
            {
                id: "2",
                session: "10:15",
                value: "10:15"
            },
            {
                id: "3",
                session: "10:30",
                value: "10:30"
            },
            {
                id: "4",
                session: "10:45",
                value: "10:45"
            },
            {
                id: "5",
                session: "11:00",
                value: "11:00"
            },
        ],
        dataTwo: [
            {
                id: "6",
                session: "10:00",
                value: "10:00"
            },
            {
                id: "7",
                session: "10:15",
                value: "10:15"
            },
            {
                id: "8",
                session: "11:30",
                value: "11:30"
            },
            {
                id: "9",
                session: "12:45",
                value: "12:45"
            },
            {
                id: "10",
                session: "13:00",
                value: "13:00"
            },
        ]
    }
}

Those are the two arrays I need to compare.

I tried the following thing:

 if(this.state.dataOne.map(item => item.session) === (this.state.dataTwo.some(item => item.session)) {
       return console.log('true');
 else {
       return console.log('false);
  }

Any suggestions? It always returns false to me....

Upvotes: 0

Views: 6550

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Array.prototype.map will return an object(array) and Array.prototype.some will return a boolean. Since you are using a strict equal, the expression will always be evaluated to false

const dataOneSession = this.state.dataOne.map(item => item.session);
const dataTwoSession = this.state.dataTwo.map(item => item.session);

let isAllValueMatched = true;

dataOneSession.forEach((value, i) => {
  if(value !== dataTwoSession[i]) {
    isAllValueMatched = false;
  }
});

if(isAllValueMatched) console.log(true);
else console.log(false);

I just corrected the code that you had given, we can write this code in an optimised way if you furnish more information like, are the arrays going to be in same length, will there be a dataThree? etc.

Upvotes: 1

Related Questions