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))

5
  • If you really want to use .forEach() then have a look at its documentation here -> Array.prototype.forEach() - JavaScript | MDN. The second argument of the callback is the index. Commented Jun 8, 2020 at 9:30
  • So, basically, you want to extract all the indexes where a specific string appears? Commented Jun 8, 2020 at 9:34
  • Thanks @Andreas, I'll take a look Commented Jun 8, 2020 at 9:41
  • @briosheje yeah that's exactly what I'm trying to do. Commented Jun 8, 2020 at 9: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. Commented Jun 8, 2020 at 9:43

1 Answer 1

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'))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.