Theme

For Loop Filtering

Filtering is the process of including/excluding items in an array based on certain condition.

You can go through all items in JavaScript using either:

  1. Traditional for loop
  2. for...of loop

for...of loop is easier to read, but you do not have access to index variable.

Exercise 1

Given an array of number, returns all the positive numbers

Examples:

  • data: [2,-3,4,-6] -> [2,4]
  • data: [-2,0,-20,-300] -> []
  • data: [12,4,3] -> [12,4,3]
export default function positiveOnly(data) {
  // TODO
}

Open browser consoleTests

Exercise 2

Given an array, returns a new array with all the undefined item removed.

Examples:

  • data: [1,3,undefined,0,12] -> [1,3,0,12]
  • data: [undefined, 'Pika', 'Charm', undefined, ''] -> ['Pika', 'Charm', '']
  • data: [undefined, undefined] -> []
export default function excludeUndefined(data) {
  // TODO
}

Open browser consoleTests

Exercise 3

Given a number, returns persons whose age larger than the number

Examples:

  • minAge: 40 -> [{ name: 'Richie', age: 50 }]
  • minAge: 51 -> []
  • minAge: 30 -> [{ name: 'Malcolm', age: 32 }, { name: 'Richie', age: 50 }]
const dataset = [
  {
    name: 'Malcolm',
    age: 32,
  },
  {
    name: 'Esther',
    age: 10,
  },
  {
    name: 'Richie',
    age: 50,
  },
  {
    name: 'Audrey',
    age: 25,
  },
];


export default function findOlderThan(minAge) {
  // TODO
}

Open browser consoleTests

Exercise 4

Given an array of number (data parameter), and a number (num parameter), returns all the indexes of the num in the data.

Examples:

  • data: [2,3,2,6], num: 2 -> [0,2]
  • data: [5,3,1], num: 6 -> []
  • data: [7,7,7], num: 7 -> [0,1,2]
export default function getPositions(data, num) {
  // TODO
}

Open browser consoleTests