Anon
Anon

Reputation: 45

Filtering data from the array

I have an example element in the table:

zxcdsa.com/photo-277590-30x24.jpeg

zxcdsa.com/photo2-254654.png

I want to reject elements that in its name (el.src) have a string of characters from e.g. 30x30 to 350x350. How can I get this effect? Filters elements using:

var newArray = someImages.filter(function (el) {
 const min = 400;
 const max = 700;
 const delimiter = 'x';
return el.width >= 400 ||
 el.class.indexOf('post-image') > -1 ||
 el.src.match( /\d+x\d+/ )[ 0 ]
   .split( delimiter )
   .every( ( number ) => {
     return number >= min && number <= max;
   });
 ....
});

This code does not work when match() cannot find the item.

Example:

Upvotes: 0

Views: 77

Answers (2)

Kingsley Mitchell
Kingsley Mitchell

Reputation: 2589

Think you are making it hard for yourself.

Logically, split the string into array, then get the numbers and if they are divisible by 10 then allow and if not then disallow

Upvotes: 0

Barmar
Barmar

Reputation: 780843

When .match() doesn't find a match it returns null, not an array, so you can't index it with [0]. So you need to break that up into a variable assignment, test that it's not null, and the rest.

You can also use capture groups in the regexp to avoid having to call split().

var newArray = someImages.filter(function (el) {
  return el.width >= 400 ||
    el.class.indexOf('post-image') > -1 ||
    ((m = el.src.match( /(\d+)x(\d+)/ )) && 
      [m[1], m[2]].every( number => number >= min && number <= max))
    ....
});

Upvotes: 1

Related Questions