-1

I know howe to do it using filter but I wondering if therei s a posibility to run this code with loop "for". Thank you for help.

function filter_list(l) {
let result = [];
  for (i = 0; i < l.length; i++) {
    if (typeof(l) === "number") {
   return l[i];
  }
 }  

}

console.log(filter_list(["abc", 1, 2, "def", 3, 4, "ghi"]));
Jakub
  • 31
  • 3
  • Does this answer your question? [Remove Strings, Keep Numbers In Array With JavaScript](https://stackoverflow.com/questions/55403168/remove-strings-keep-numbers-in-array-with-javascript) – Ivar Mar 09 '21 at 12:47

2 Answers2

0

You could filter by check the finiteness of the value.

function filter_list(l) {
    return l.filter(Number.isFinite);
}

console.log(filter_list(["abc", 1, 2, "def", 3, 4, "ghi"]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I know howe to do it using filter but I wondering if therei s a posibility to run this code with loop "for". Thank you for help. – Jakub Mar 09 '21 at 12:50
  • @Jakub you can push the value to result when type is number and return that result list in the last. – gorak Mar 09 '21 at 12:51
0

You have a number of errors in your code that are causing it not to work as intended.

  • In your condition you are testing if the typeof the passed array is 'number' rather than each element.
  • next, you don't want to return on true matches, instead you want to push the element to result.
  • last, you need to declare i

function filter_list(l) {
  let result = [];
  for (let i = 0; i < l.length; i++) {
    let element = l[i];
    if (typeof element === "number") {
      result.push(element);
    }
  }
  return result;
}

console.log(filter_list(["abc", 1, 2, "def", 3, 4, "ghi"]));
pilchard
  • 12,414
  • 5
  • 11
  • 23