OneCompiler

Modify the above program to keep even numbers only while flattening. Make it so that the condition for filtering (e.g. even number, odd number, multiples of 3, …) is changeable.

237

const treeList = [1, 2, 3, 4, 5, 6, 12, 8, 13, 14, 15];

const flattenedNums = [];

const flattenNumbers = (type) => {
for (let i = 0; i < treeList.length; i++) {
if (type === 'even') {
if (treeList[i] % 2 === 0) {
flattenedNums.push(treeList[i]);
}
} else if (type === 'odd') {
if (treeList[i] % 2 !== 0) {
flattenedNums.push(treeList[i]);
}
} else if (type === 'multiplesOfThree') {
for (let j = 0; j < treeList.length; j++) {
if (treeList[j] === 3 * (i + 1)) {
flattenedNums.push(treeList[j]);
}
}
}
}
};

flattenNumbers('multiplesOfThree');
console.log('----x------x-------', flattenedNums && flattenedNums);