I am using React's componentDidUpdate
lifecycle method.
I am trying to determine whether or not two arrays are the same.
My prevState
array looks like this:
prevState.players = [
{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
and the this.state
array looks like this:
this.state.players = [
{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
As you can see if you expand the snippet below they are not equal:
let playersOne = [{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
let playersTwo = [{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
console.log(playersOne == playersTwo)
And here is my react lifecycle code.
componentDidUpdate(prevProps, prevState) {
if(prevState.players != this.state.players) {
this.updatePlayers(this.state);
}
}
can anyone advise as to the best way to determine if the arrays are equal?
You can use array#every to check if both objects have the same number of objects and each object has the same number of key and values.
Use the spread syntax (...) to merge arrays in React, e.g. const arr3 = [...arr1, ...arr2] . The spread syntax is used to unpack the values of two or more arrays into a new array. The same approach can be used to merge two or more arrays when setting the state. Copied!
To remove the duplicates from an array in React, pass the array to the Set constructor, e.g. [... new Set(arr)] . Each value in a Set has to be unique, so any duplicates get automatically removed. Copied!
JSON.stringify(playersOne) == JSON.stringify(playersTwo)
You can use array.prototype.every
:
var players = [
{ name: 'Wayne Rooney' , age: 31 },
{ name: 'Lionel Messi' , age: 29 },
{ name: 'Robbie Fowler' , age: 42 }
];
var statePlayers = [
{ name: 'Wayne Rooney' , age: 31 },
{ name: 'Lionel Messi' , age: 29 },
{ name: 'Robbie Fowler' , age: 42 }
];
var equals = players.length === statePlayers.length && players.every((e, i) => e.name === statePlayers[i].name && e.age === statePlayers[i].age);
console.log(equals);
Alternatively, using object destructuring and Array.prototype.some
.
const
players = [
{ name: 'Wayne Rooney' , age: 31 },
{ name: 'Lionel Messi' , age: 29 },
{ name: 'Robbie Fowler' , age: 42 }
],
statePlayers = [
{ name: 'Wayne Rooney' , age: 31 },
{ name: 'Lionel Messi' , age: 29 },
{ name: 'Robbie Fowler' , age: 42 }
],
playersEqual = (expected, actual) =>
actual.length === expected.length &&
!expected.some(({ name, age }, i) =>
(({ name: otherName, age: otherAge }) =>
name !== otherName || age !== otherAge)
(actual[i]));
console.log(playersEqual(players, statePlayers));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With