Home > Software engineering >  Why is the || not working in this if/else statement?
Why is the || not working in this if/else statement?

Time:06-22

I created a filter function to filter out certain codes in a spreadsheet. However, the list is very, very long (say around 50) and when I add a bunch of "else ifs" Google doesn't like it and the function fails.

var bldgFilter = function(item) {
  if(item[1] == "TA12") {
    return true;
  } else if (item[1] == "DA06") {
    return true;
  } else {
    return false;
  }
}

However, when I try this, it doesn't work at all. Is there something I'm missing?

var bldgFilter = function(item) {
  if(item[1] == "TA12" || "DA06") {
    return true;
  } else {
    return false;
  }
}

This is the original array and I am trying to filter out the 1D arrays that include certain elements in the second position:

[[123730, PH02, 1245, 1745, 1630, 1.0], [122857, PH01, 1300, 1800, 2145, 1.0], [125116, TA12, 1300, 1800, 1830, 1.0], [122077, DA04, 1330, 1830, 2230, 1.0], [124376, VP02, 1400, 1900, 2300, 1.0], [119588, SC03A, 1430, 1930, 2230, 1.0], [122248, MP01, 1430, 1930, 2330, 1.0], [124551, VG02, 1630, 2130, 1900, 1.0], [125130, DA06, 1630, 2130, 0230, 2.0], [122979, SY01, 1700, 2200, 2300, 1.0], [123437, PH01, 1730, 2230, 0300, 1.0], [124137, BA06, 1730, 2230, 0130, 1.0], [124953, BA09, 1730, 2230, 0300, 3.0]]

CodePudding user response:

A much better way of doing this would be something like:

const data = [[123730, 'PH02', 1245, 1745, 1630, 1.0], [122857, 'PH01', 1300, 1800, 2145, 1.0], [125116, 'TA12', 1300, 1800, 1830, 1.0], [122077, 'DA04', 1330, 1830, 2230, 1.0], [124376, 'VP02', 1400, 1900, 2300, 1.0], [119588, 'SC03A', 1430, 1930, 2230, 1.0], [122248, 'MP01', 1430, 1930, 2330, 1.0], [124551, 'VG02', 1630, 2130, 1900, 1.0], [125130, 'DA06', 1630, 2130, 0230, 2.0], [122979, 'SY01', 1700, 2200, 2300, 1.0], [123437, 'PH01', 1730, 2230, 0300, 1.0], [124137, 'BA06', 1730, 2230, 0130, 1.0], [124953, 'BA09', 1730, 2230, 0300, 3.0]]
const matches = ['TA12', 'DA06'];
const filtered_data = data.filter(x => matches.includes(x[1]))
console.log(filtered_data)

  • Related