Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

53
Views
How to check if a value is equal to exactly one value from an array

I have the following array:

const person = [
      { name: "John", surname: "Doe" },
      { name: "Jane", surname: "Williams" }];

I want to check if a match is equal to just one name from the array. I did the following:

match === person[0].name || match === person[1].name || match === person[3].name ? "Do something" : "Blank"

I'm looking for a better way to iterate through this array, because I don't know array length.

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

person.forEach(function(item){
if(match === item.name){
// your logic goes here
}
})

this iterates through every object("{}") in your array and executes a function (you could use an arrow function too). The function then checks if your "match" value is equal to the "name" key in every object(referenced by "item") in the array it had ran through.

There are other array methods you can check out.

7 months ago · Juan Pablo Isaza Report

0

You can use Array.prototype.find to find in an array of objects.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

As a demonstration, I have written a search persons by name form:

const persons = [
  { name: "John", surname: "Doe" },
  { name: "Jane", surname: "Williams" }
]

function bindEvent() {
  const form = document.forms['find-by-name-form']
  form.addEventListener('submit', onSubmit, true)
}

function onSubmit(event) {
  event.preventDefault()
  const { name } = event.target
  const person = findPersonByName(name.value)
  alert(person ? `${person.name} ${person.surname}` : 'no result')
  person && console.log(person)
}

function findPersonByName(name) {
  return persons.find((item) => item.name === name)  
}

window.onload = bindEvent
<form name="find-by-name-form">
  <label for="name">Find by name:</label>
  <input name="name" />
  <button>Search person</button>
</form>

7 months ago · Juan Pablo Isaza Report

0

Best solution to find index of array of match value const name = 'sandeep'

const match = persons.findindex

((person) => person.name === name)

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.