期待値は
0,2,3 です。
ふむふむ。であれば
javascript
1const array = [ 25, 15, 40, 70, 20 ];
2const M = 25;
3
4const passIndexes = array.reduce((ary, e, i) => e >= M ? [...ary, i] : ary, []);
5
6console.log(passIndexes); // => [0, 2, 3]
とかですかね〜
【別案1】再帰関数
javascript
1const findIndexes = (ary, min, start=0) => {
2 const index = ary.findIndex(e => e >= min);
3 return index >= 0 ? [start+index, ...findIndexes(ary.slice(index+1), min, start+index+1)] : [];
4}
というのを作っておいて、
javascript
1const array = [ 25, 15, 40, 70, 20 ];
2const M = 25;
3const passIndexes = findIndexes(array, M);
4
5console.log(passIndexes); // => [0, 2, 3]
とする。
【別案2】mapしてfilterしてまたmapするっていう3工程になってしまうけれど、
javascript
1const array = [ 25, 15, 40, 70, 20 ];
2const M = 25;
3const passIndexes = array.map((e, i) => ({ e, i })).filter(({ e }) => e >= M).map(({ i }) => i);
4
5console.log(passIndexes); // => [0, 2, 3]
【別案3】上の【別案2】を見直したらmapとfilterの2工程で済みました。
javascript
1const array = [ 25, 15, 40, 70, 20 ];
2const M = 25;
3const passIndexes = array.map((e, i) => e >= M ? i : -1).filter(n => n >= 0);
4
5console.log(passIndexes); // => [0, 2, 3]