0

Can anyone help me regarding the following issue:

If I have the following array:

sports = new Array('rugby','tennis','football','snooker','cricket','football');

How can I find the number of occurrences of 'football' within the array and return the index's - in this case 2 & 5;

I know I could do this with a simple for/next loop but on the end project the array will be a lot bigger and pondered if there is another way to do it.

Thanks in advance.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
London28
  • 21
  • 2
  • 2
    You have to check every element, hence you have to use some form of a loop. What's the problem with that? o.O – Andreas May 11 '21 at 16:35
  • [jquery] is for DOM manipulation - anything you use here will(*) be vanilla javascript. (*) jquery does have some array manipulation methods, mostly they were available before the js equivalents. – freedomn-m May 11 '21 at 16:55
  • You might be looking for [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) - but it won't return the indexes. – freedomn-m May 11 '21 at 16:57
  • Lots of options in the closed question (mostly with loops and creating new arrays) - didn't see this solution: `sports.map((e, i) => e === "football" ? i : 0).filter(e => e != 0);` (nor this specific scenario (return the indexes) – freedomn-m May 11 '21 at 17:01
  • 1
    Thanks, the above is perfect. – London28 May 11 '21 at 18:00

0 Answers0