简体   繁体   中英

Remove random strings from an array , JavaScript

I need to remove strings from an array and i have this function; It makes some random tests and returns a result.

function filter_list(array) {
 array.filter((elem) => typeof elem === "string");
 return (array);
}

When i don't return anything i get undefined (obviously), but when i return the array i get this:

"Expected: '[1, 2]', instead got: '[1, 2, \'a\', \'b\']'
Expected: '[1, 0, 15]', instead got: '[1, \'a\', \'b\', 0, 15]'
Expected: '[1, 2, 123]', instead got: '[1, 2, \'aasf\', \'1\', \'123\', 
123]'
Expected: '[]', instead got: '[\'a\', \'b\', \'1\']'
Expected: '[1, 2]', instead got: '[1, 2, \'a\', \'b\']' " 

You are misusing twice the array filter .

The first problem is that the array doesn't change when you call filter.

// This code isn't the correct yet, continue below
function filter_list(array) {
  // You have to return the result of filter. The 'array' is not changed.
  return array.filter((elem) => typeof elem === "string");
}

The second problem is that you are filtering the opposite you want to filter.

// Correct code
function filter_list(array) {
  // If the condition is true, the element will be kept in the NEW array.
  // So it must be false for strings
  return array.filter((elem) => typeof elem !== "string");
}

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true . callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

It's pretty easy though. Here's how you will do it

 let data = [ "Cat", 1451, 14.52, true, "I will be removed too :(" ]; let filteredData = data.filter(item => typeof item !== "string"); console.log(filteredData); // or return it 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM