Проверка свойсва и выход из функции
Есть функция которая добавляет новый контакт в массив, надо проверить есть такое имя или нет. Мой вариант норм? Или как можно проще записать?
let contacts = [{name: 'asd'}]
let newContact = {name:'asd'}
function check() {
const sameName = contacts.map(e => e.name).includes(newContact.name);
if (sameName) {
console.log('true')
return;
} else {console.log('false')}
}
check(newContact)
Ответы (1 шт):
Автор решения: Алексей Шиманский
→ Ссылка
let contacts = [{name: 'asd'}]
let newContact = {name:'asd'}
function check(newContact) {
const sameName = contacts.find(e => e.name === newContact.name);
return sameName !== undefined;
}
console.log(check(newContact));
или
let contacts = [{name: 'asd'}]
let newContact = {name:'asd'}
function check(newContact) {
return contacts.some(e => e.name === newContact.name);
}
console.log(check(newContact));