0

This is my array

let a = [{"id":1,"barcode":"8851907264888"},{"id":2,"barcode":"8857124022072"}];

I want to input a barcode and check that if the input barcode is exist in array or not, what should I do?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Jack Venevankham
  • 147
  • 2
  • 12
  • Have you tired this : https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add/22844712 – Mohit Jul 29 '20 at 07:29
  • Does this answer your question? [Check if object value exists within a Javascript array of objects and if not add a new object to array](https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add) – Mohit Jul 29 '20 at 07:29

1 Answers1

0

Array::some

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

arr.some(el => el.barcode === barcodeToSearch);

const a = [{
  "id": 1,
  "barcode": "8851907264888"
}, {
  "id": 2,
  "barcode": "8857124022072"
}];

const hasBarcode = (arr, barcode) => arr.some(el => el.barcode === barcode);

const barcode1 = "1234567890123";
const barcode2 = "8857124022072";

console.log(hasBarcode(a, barcode1)); // false
console.log(hasBarcode(a, barcode2)); // true
Drew Reese
  • 165,259
  • 14
  • 153
  • 181