Получите года, сумма цифр которых равна 6
Помогите решить задачку.
Дан список с годами:
<ul>
<li>2001</li>
<li>2004</li>
<li>2021</li>
<li>2012</li>
<li>2035</li>
<li>2031</li>
Получите года, сумма цифр которых равна 6.
Нужно средствами JS решить данную задачу. Я ещё в процессе изучения языка и поэтому застрял на пару дней уже.
Ответы (3 шт):
Автор решения: 4efirrr
→ Ссылка
// Function to compute the sum of digits in a number
function sumOfDigits(num) {
let sum = 0;
// Keep adding the last digit of the number to the sum and remove it until there are no digits left
while (num) {
sum += num % 10;
num = Math.floor(num / 10);
}
return sum;
}
// Initial list of years
const yearsList = document.querySelector('ul');
const years = Array.from(yearsList.children).map(li => parseInt(li.textContent));
// Filter the list of years to include only the ones whose sum of digits is 6
const filteredYears = years.filter(year => sumOfDigits(year) === 6);
console.log('Result: ' + filteredYears); // [2004, 2031]
<ul>
<li>2001</li>
<li>2004</li>
<li>2021</li>
<li>2012</li>
<li>2035</li>
<li>2031</li>
</ul>
Автор решения: Alexander Lonberg
→ Ссылка
const items = [...document.querySelectorAll('ul>li')] // получаем все li
.map(({textContent}) => textContent.trim()) // извлекаем текст
.filter((text) => // фильтруем по условию
[...text] // разбиваем на цифры
.map((v) => Number.parseInt(v)) // ... и переводим в number
.reduce((a, v) => a += v, 0) === 6 // складываем и проверяем условие
)
console.log(items)
<ul>
<li>2001</li>
<li>2004</li>
<li>2021</li>
<li>2012</li>
<li>2035</li>
<li>2031</li>
<ul>
Автор решения: user604907
→ Ссылка
let elems = document.querySelectorAll('li');
let sum2 = 0;
for(let elem of elems ){
let arr = elem.textContent.split('');
let sum = 0;
for( el of arr){
sum += Number(el);
}
if(sum === 6){
sum2 +=sum;
}
}
console.log(sum2);