我有一個包含一些物件的陣列我想在陣列中找到重復的名稱在找到每個重復名稱的重復名稱后,我還應該檢查它們的年齡。除了同名,如果年齡不一樣但是名字都一樣,保存下來,只有名字一樣,同齡才報錯。我的陣列有重復的名字,年齡不同 現在我寫的程式給出了錯誤,不應該給出錯誤,因為名字是相同的,但他們的年齡不一樣,應該保存,但在搜索陣列后沒有正確完成,我發現重名。兩個重復的 Liam 名字的年齡相等。在console里報錯,但是如果年齡不相等,不要報錯,會報錯謝謝大家幫我解答
const data = [
{id: 1,name: "Liam",age: 20},
{id: 2,name: "Liam",age: 18},
{id: 3,name: "Noah",age: 20},
{id: 4,name: "Noah",age: 18},
{id: 5,name: "Elijah",age: 18}
]
function checked() {
const toFindDuplicates = arry => arry.filter((item, index) => arry.indexOf(item) !== index);
const getName = data.map(item => item.name)
const duplicateName = toFindDuplicates(getName)
console.log(duplicateName);
if (duplicateName.length > 0) {
const newArray = []
const filters = data.filter(x => duplicateName.includes(x.name))
filters.forEach(item => newArray.push(item.age))
console.log(filters);
const duplicateAge = toFindDuplicates(newArray)
if (!!duplicateName.length) {
console.log("error");
} else {
return console.log("save");;
}
} else {
return console.log("save");;
}
}
checked()
uj5u.com熱心網友回復:
If I understood your question correctly, you simply want to detect if your data has the same name age pair. You can check it like this:
const data1 = [
{id: 1,name: "Liam",age: 20},
{id: 2,name: "Liam",age: 18},
{id: 3,name: "Noah",age: 20},
{id: 4,name: "Noah",age: 18},
{id: 5,name: "Elijah",age: 18}
]
const data2 = [
{id: 1,name: "Liam",age: 20},
{id: 2,name: "Liam",age: 18},
{id: 3,name: "Noah",age: 20},
{id: 4,name: "Noah",age: 18},
{id: 5,name: "Elijah",age: 18},
{id: 6,name: "Liam",age: 18},
]
const duplicateExists = arr => {
let error = false, obj = {}
arr.forEach(el => {
if(!error){
const {name,age} = el
if(obj[name]) {
error = obj[name] === age
}
obj[name] = age
}
} ,{})
return error
}
console.log(duplicateExists(data1))
console.log(duplicateExists(data2))
uj5u.com熱心網友回復:
For an O(N) single-pass solution you could consider utilizing a Map that uses the name as a key and a Set of previously seen ages corresponding to the name as the value, since lookup into a Set is O(1):
const data = [
{id: 1, name: "Liam", age: 20},
{id: 2, name: "Liam", age: 18},
{id: 3, name: "Noah", age: 20},
{id: 4, name: "Noah", age: 18},
{id: 5, name: "Elijah", age: 18},
];
const hasDuplicates = arr => {
const nameToAges = new Map();
for (const {_, name, age} of arr) {
if (nameToAges.has(name)) {
if (nameToAges.get(name).has(age)) {
return true;
}
nameToAges.get(name).add(age);
} else {
nameToAges.set(name, new Set([age]));
}
}
return false;
}
console.log("Two elements exist with same name and age:");
console.log(hasDuplicates(data));
Try it out here.
uj5u.com熱心網友回復:
The description of your issue is not entirely clear to me, but it sounds like you want to group the items based on name. Then do some checks based on the resulting groups.
const data = [
{ id: 1, name: "Liam", age: 18 },
{ id: 2, name: "Liam", age: 18 },
{ id: 3, name: "Noah", age: 20 },
{ id: 4, name: "Noah", age: 18 },
{ id: 5, name: "Elijah", age: 18 },
];
const peopleByName = groupBy(data, person => person.name);
for (const [name, people] of peopleByName) {
const isDuplicate = people.length > 1;
const haveSameAge = people.every(person => person.age == people[0].age);
if (isDuplicate && haveSameAge) {
console.log(name, "is a duplicate");
} else if (isDuplicate) {
console.error(name, "duplicate with different ages");
} else {
console.log(name, "is unique");
}
}
// helper
function groupBy(iterable, fnKey) {
const groups = new Map();
for (const item of iterable) {
const key = fnKey(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
uj5u.com熱心網友回復:
Here's a check for duplicate records (name and age) in the array, using a reducer function on the entries the data. For methods used, study
- Array.reduce
- Object.entries
- Object.fromEntries
- Array.filter
const data = [
{id: 1,name: "Liam",age: 20},
{id: 2,name: "Liam",age: 18},
{id: 3,name: "Noah",age: 20},
{id: 13,name: "Noah",age: 20},
{id: 4,name: "Noah",age: 18},
{id: 5,name: "Elijah",age: 18},
{id: 12,name: "Elijah",age: 18}
];
const duplicateCheck = data => Object.fromEntries(
Object.entries( data.reduce( (acc, r) => {
const okRec = acc[`${r.name}${r.age}`]
? { [`id${r.id}`]: `Name: ${r.name}, age: ${r.age} => more then once` }
: { [`${r.name}${r.age}`]: `ok` };
return {... acc, ...okRec };
}, {} ) )
.filter( ([key, value]) => value.endsWith(`more then once`) )
);
console.log(duplicateCheck(data));
// to only determine if the data array contains duplicates according
// to your criteria (name, age) use:
console.log(`[data] has duplicates? ${
Object.keys(duplicateCheck(data)).length > 0}`);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/310073.html
標籤:javascript
上一篇:用固定值計算輸入值
