Why function cannot read array element in loop? [closed]

I have a simple function that only checks if the fourth element of an array is bigger or not.

Somehow I am getting and error TypeError: Cannot read property '3' of undefined

And I have no idea why… Can someone tell me what is wrong with this function?

var pasujace = [
  ["BLANK", "A4205022", "L00063746", 1000.0],
  ["BLANK", "A4205022", "L00063743", 100.0],
  ["BLANK", "A4205022", "L00063743", 100.0],
  ["BLANK", "A4205022", "L00056983", 300.0]
];
var roznica = 50;

function lastOne(arr, num) {
  var nowa = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i][3] > num) {
      nowa.push(arr[i]);
    }
  }
  return nowa
}

const last = lastOne(pasujace, roznica);
console.log(last)

Answer

Use a filter

var pasujace = [
  ["BLANK", "A4205022", "L00063746", 1000.0],
  [],
  ["BLANK", "A4205022", "L00063743", 100.0],
  ["BLANK", "A4205022", "L00063743", 100.0],
  ["BLANK", "AAA"],
  ,
  ["BLANK", "AAA", "MISSING"],
  ["BLANK", "A4205022", "L00056983", 300.0]
];
var roznica = 100;

const lastOne = (arr, num) => arr.filter(item => {
  if (!item || item.length < 3 || isNaN(item[3])) return false;
  return item[3] > num
});


const last = lastOne(pasujace, roznica);
console.log(last)

Leave a Reply

Your email address will not be published. Required fields are marked *