简体   繁体   中英

Check if a value is equal with another

I have some code that should loop through an array of objects and if the name value is repeated anywhere in array, the code should display "repeatedName". If not "not repeatedName".

 export default function App() { const arr = [ { name: "John", age: 22 }, { name: "Julia", age: 28 }, { name: "John", age: 22 }, { name: "Bill", age: 22 } ]; return ( <div className="App"> {arr.map((i, k) => ( <p> {arr[k + 1].== undefined && i.name === arr[k + 1]?name: "repeatedName"; "not repeatedName"} </p> ))} </div> ); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Now i get this:

 not repeatedName not repeatedName not repeatedName not repeatedName

But the expected result is:

 not repeatedName not repeatedName repeatedName not repeatedName
demo: https://codesandbox.io/s/unruffled-shaw-0mdxi?file=/src/App.js:450-462 How to change my code to get the described result?

In order to get the duplicates, you will need to store the unique names in another array, then reference that array within the loop of the object.

The following will loop through the object and add the name of the person to the array. Then when it continues through the loop, the name is checked with names we already know about.

 const uniqueNames = [] const people = [ { name: "John", age: 22 }, { name: "Julia", age: 28 }, { name: "John", age: 22 }, { name: "Bill", age: 22 } ] people.forEach((person) => { if (uniqueNames.indexOf(person.name) > -1) { console.log('Repeated') return } uniqueNames.push(person.name) console.log('Not repeated') })

Here's another take on the task (just for the heck of it): (Carl's solution is a more elegant one)

  const arr = [
    {
      name: "John",
      age: 22
    },
    {
      name: "Julia",
      age: 28
    },
    {
      name: "John",
      age: 22
    },
    {
      name: "Bill",
      age: 22
    }
  ];


  return (
    <div className="App">

      {arr.map((i,k)=>{

          const isFound = k-1 > 0 && arr.slice(0, k-1).some( el => {
            return el.name === i.name; 
          })
          return isFound ? <p>repeatedName</p> : <p>not repeatedName</p>
      })}

    </div>
  );
}

Assuming you want to check if the name previously appeared anywhere in the array, you can do this with map - but it's going to look fairly clumsy and inelegant:

{arr.map((i, k) => (
    <p>
      {arr[k - 1] !== undefined && arr.slice(0, k).some(obj => obj.name === arr[k].name) 
        ? "repeatedName"
        : "not repeatedName"}
    </p>
))}

Although I am in general a fan of the "functional style" using map and so on, here I think it's more appropriate to use a more imperative style with a loop and some internal state:

const getRepeatedStates = arr => {
    const names = [];
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        const currentName = arr[i].name;
        result.push(names.includes(currentName) ? "repeatedName" : "not repeatedName";
        names.push(currentName);
    } 
    return result;
}

And then in your returned JSX, use

{getRepeatedStates(arr).map(text => (<p>{text}</p>)} 

There is a handy JavaScript object that makes it very easy to identify duplicates like these.

It's called Set . Use Set.prototype.add() to add to the set, and Set.prototype.has() to determine if a value is in the set. A value can exist only once in a Set.

 const arr = [ { name: "John", age: 22 }, { name: "Julia", age: 28 }, { name: "John", age: 22 }, { name: "Bill", age: 22 } ]; const nameSet = new Set(); let nameStats = arr.map(el => { let status = nameSet.has(el.name)? "repeatedName": "not repeatedName"; nameSet.add(el.name); return status; }); console.log('nameStats:', nameStats);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM