0

Very new to Javascript and coding in general!

I'm basically looking to test strings within an array, if and when a string returns a certain value I then want to get the index of that string within the array and store the indexes within another variable.

The problem I'm having (I think) is that I'm unsure of the correct syntax to extract and push the index once I've confirmed that it's the string I'm looking for ... Apologies in advance if I've not explained myself very well.

Here's what I have:

let freightItems = ['contraband', 'clear', 'contraband', 'clear'];

function scan(freightItems) {

  let contrabandIndexes = [];
  
  freightItems.forEach(str => {
    if (str === 'contraband') {
        freightItems.push(contrabandIndexes);
    }
  })
  
  return contrabandIndexes;
}

console.log(scan(freightItems))
Alex L
  • 4,168
  • 1
  • 9
  • 24
  • If you really want to use `.forEach()` then have a look at its documentation here -> [Array.prototype.forEach() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). The second argument of the callback is the index. – Andreas Jun 08 '20 at 09:30
  • So, basically, you want to extract all the indexes where a specific string appears? – briosheje Jun 08 '20 at 09:34
  • Thanks @Andreas, I'll take a look – Goot_Warren Jun 08 '20 at 09:41
  • @briosheje yeah that's exactly what I'm trying to do. – Goot_Warren Jun 08 '20 at 09:42
  • @Goot_Warren then it's just enough to use the second parameter of the `.forEach` callback function, which conveniently is the index of the currently iterated item, which is what you're looking for. – briosheje Jun 08 '20 at 09:43

1 Answers1

0

You could do it like this (with forEach):

(Note, it is a good idea to make your function more generic by allowing it to scan for any searchText and not hard coding 'contraband')

let freightItems = ['contraband', 'clear', 'contraband', 'clear'];

function scan(freightItems, searchText) {

  let contrabandIndexes = [];
  
  freightItems.forEach((str, index) => {
    if (str === searchText) {
        contrabandIndexes.push(index);
    }
  })
  
  return contrabandIndexes;
}

console.log(scan(freightItems, 'contraband'))

Output

[0, 2]

You could also do it like this (with reduce):

let freightItems = ['contraband', 'clear', 'contraband', 'clear'];

function scan(freightItems, searchText) {
 
  return freightItems.reduce((aggArr, str, index) => {
    if (str === searchText) {
        aggArr.push(index);
    }
    return aggArr;
  }, [])
}

console.log(scan(freightItems, 'contraband'))
Alex L
  • 4,168
  • 1
  • 9
  • 24