![](/img/trans.png)
[英]How to check if a value is not equal to another value in the array using javascript
[英]Check if a value is equal with another
我有一些代碼應該遍歷一個對象數組,如果name
值在數組中的任何地方重復,代碼應該顯示“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>
現在我明白了:
not repeatedName not repeatedName not repeatedName not repeatedName
但預期的結果是:
not repeatedName not repeatedName repeatedName not repeatedName
為了獲得重復項,您需要將唯一名稱存儲在另一個數組中,然后在 object 的循環中引用該數組。
下面將循環遍歷 object 並將此人的姓名添加到數組中。 然后,當它繼續循環時,將使用我們已經知道的名稱檢查名稱。
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') })
這是另一個任務(只是為了它):(Carl 的解決方案更優雅)
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>
);
}
假設您想檢查該名稱以前是否出現在數組中的任何位置,您可以使用map
來執行此操作 - 但它看起來相當笨拙和不優雅:
{arr.map((i, k) => (
<p>
{arr[k - 1] !== undefined && arr.slice(0, k).some(obj => obj.name === arr[k].name)
? "repeatedName"
: "not repeatedName"}
</p>
))}
雖然我通常是使用map
等的“函數式風格”的粉絲,但在這里我認為使用帶有循環和一些內部 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;
}
然后在你返回的 JSX 中,使用
{getRepeatedStates(arr).map(text => (<p>{text}</p>)}
有一個方便的 JavaScript object 可以很容易地識別像這樣的重復項。
它叫做Set 。 使用Set.prototype.add()
添加到集合中,使用Set.prototype.has()
確定值是否在集合中。 一個值在 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.