How To Determine If Javascript Array Contains An Object With An Attribute That Is Equal To Each Other
I have an array like
selectedData = [{
Name = 'Michelle',
LRN = '100011'
},
{
Name = 'Micheal',
LRN = '100011'
},
{
Name = 'Mick',
LRN = '100012'
} // so on....
]
I am sending this array through a function and that simply checks if the LRN attribute of each object is same if not it throws error. I have written the function as -
createSet(selectedData) {
this.selectedData.forEach (element => {
//the condition
}
else
{
this.openSnackBar ("LRN mismatching");
}
}
How do I check if the LRN attribute of each object is same? I don't want loop unless I have to. I'm working with more than thousand records. I appreciate all the help. :)
Answer
You could take Array#every
and check the first item to each other. The method stops the iteration if the condition is false
and returns then false
, if not then true
.
The callback's parameter can have three parts, one for the item, the next for the index and the third one has the reference to the array.
In this case only the item is used with a destructuring of LRN
and the array. The unneeded index is denoted by an underscore, which is a valid variable name in Javascript.
if (!array.every(({ LRN }, _, a) => LRN === a[0].LRN)) {
this.openSnackBar ("LRN mismatching");
}
Code with example of all property LRN
having the same value.
const
selectedData = [{ Name: 'Michelle', LRN: '100011' }, { Name: 'Micheal', LRN: '100011'}, { Name: 'Mick', LRN: '100011' }];
if (!selectedData.every(({ LRN }, _, a) => LRN === a[0].LRN)) {
console.log("LRN mismatching");
} else {
// just to show
console.log('OK');
}
Mismatching
const
selectedData = [{ Name: 'Michelle', LRN: '100011' }, { Name: 'Micheal', LRN: '100011'}, { Name: 'Mick', LRN: '100012' }];
if (!selectedData.every(({ LRN }, _, a) => LRN === a[0].LRN)) {
console.log("LRN mismatching");
} else {
// just to show
console.log('OK');
}
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM