Как получить правильный массив
Есть массив, состоящий из букв латинского алфавита. С помощью метода indexOf нужно получить только индексы буквы ‘a’. То есть исходя из примера консоль должна выдать такой результат: [0, 1, 2, 4]. Реализовать перебор нужно именно с for().
function n(array) {
let indices = [];
let element = 'a';
let idx = array.indexOf(element);
for (let i = 0; i <= array.length; i++) {
indices.push(idx[i]);
}
return indices
}
console.log(n(['a', 'a', 'a', 'c', 'a', 'd']))
Ответы (2 шт):
Автор решения: vsemozhebuty
→ Ссылка
Условия, конечно, искусственные, ну, на то оно и учебное задание) Можно так:
function n(array) {
const indices = [];
const element = 'a';
for (let i = 0; i < array.length; ) {
const index = array.indexOf(element, i);
if (index > -1) {
indices.push(index);
i = index + 1;
} else {
break;
}
}
return indices;
}
console.log(n(['a', 'a', 'a', 'c', 'a', 'd']));
P.S.: когда перебираете массив, используйте i < array.length, а не i <= array.length, иначе выйдете за границы массива.
Автор решения: entithat
→ Ссылка
const el = 'a';
const n = (a) => a.reduce((ac, c, i) => {
if (c === el) ac.push(i);
return ac;
}, []);
console.log(n(['a', 'a', 'a', 'c', 'a', 'd']));
console.log(n(['d', 'c', 'b', 'a']));
Либо так:
const el='a';
const n=(a)=>a.map((e,i)=>e===el?i:null).filter(Number.isInteger);
console.log(n(['a', 'a', 'a', 'c', 'a', 'd']));
console.log(n(['d', 'c', 'b', 'a']));
Либо по условия задачи с циклом:
const el = 'a';
const n = (a) => {
const acc = [];
for (const [i, e] of a.entries())
if (e === el) acc.push(i);
return acc;
};
console.log(n(['a', 'a', 'a', 'c', 'a', 'd']));
console.log(n(['d', 'c', 'b', 'a']));
Либо по условию задачи с циклом while и indexOf:
const el = 'a';
const n = (a) => {
const acc = [];
let i = -1;
while ((i = a.indexOf(el, i + 1)) != -1)
acc.push(i);
return acc;
};
console.log(n(['a', 'a', 'a', 'c', 'a', 'd']));
console.log(n(['d', 'c', 'b', 'a']));
Либо по условию задачи с циклом for и indexOf:
const el = 'a';
const n = (a) => {
const acc = [];
let i = -1;
for (i=a.indexOf(el); i != -1; i = a.indexOf(el, i + 1))
acc.push(i);
return acc;
};
console.log(n(['a', 'a', 'a', 'c', 'a', 'd']));
console.log(n(['d', 'c', 'b', 'a']));