JS_HOME_WORK/46-push-to-array-if-not-exists/solution.js
2025-01-17 01:00:07 +01:00

34 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** ЗАДАЧА 46 - Добавление уникальных элементов в массив
*
* 1. Создайте функцию "pushIfUnique" с двумя параметрами "inputArray" и "newElement"
*
* 2. Если "inputArray" уже содержит "newElement",
* выведите в консоль "{newElement} уже находится в массиве"
*
* 3. В противном случае добавьте "newElement" в "inputArray"
*
* ПРИМЕЧАНИЕ: Мы предполагаем, что "inputArray" содержит элементы только примитивных типов
*/
const pushIfUnique = (inputArray, newElement) => {
if (inputArray.includes(newElement)) {
return console.log(`${newElement} уже находится в массиве`)
}
inputArray.push(newElement)
}
const myNumbers = [123, 50, 27]
pushIfUnique(myNumbers, 50) // "50 уже в массиве"
console.log(myNumbers) // [123, 50, 27]
pushIfUnique(myNumbers, 80)
console.log(myNumbers) // [123, 50, 27, 80]
pushIfUnique(myNumbers, 80) // "80 уже в массиве"
console.log(myNumbers) // [123, 50, 27, 80]
pushIfUnique(myNumbers, 77)
console.log(myNumbers) // [123, 50, 27, 80, 77]