DevMountain- Match Values in Array
by Matthew Day
HTML
<div id="feedback"></div>
JavaScript
// OBJECTIVE: Find only the falsy values in 'mixedArray' and add them to 'newArray'.
var mixedArray = ['Dog', 0, undefined, "multiple words", NaN, 10, false, true, 1, null];
function falsyFilter() {
var newArray = [];
var falsyValues = [0, undefined, NaN, false, null];
for(var i = 0; i < falsyValues.length; i++) {
if(mixedArray.indexOf(falsyValues[i]) == -1) {
newArray.push(falsyValues[i]);
}
else { newArray.push(falsyValues[i]); }
}
return newArray
}
var runFunction = falsyFilter();
var showResult = document.getElementById('feedback');
showResult.textContent = runFunction;
// The loop cycles through all of the values in the array 'falsyValues' and checks these values against all of the values in the 'mixedArray'. When it finds a match, it pushes the matched values to the array 'newArray'.
// The first part of the IF statement checks to see if there is a match for 'NaN'. NaN has some peculiar qualities (see http://adripofjavascript.com/blog/drips/the-problem-with-testing-for-nan-in-javascript.html), so the first part is dedicated to looking for 'NaN' only and nothing else. The second part of the IF statement looks to see if there are matches for the other types of falsy values.
// I'm not convinced this is the best way to do this but it works.