MarsMan
MarsMan

Reputation: 13

indexOf element in array problem [google apps script]

I'm pretty new to programming with GAS and I believe that the solution should be simple. However...

An array named listWP is basically return value of some function and parsed as an argument to another function. Inside array are various strings, some marked with "c-". I need to find the first and last element with such marking. But I'm allways getting -1 as the result. The code is:

Logger.log(Array.isArray(listWP));   //returns true
var firstC=listWP.indexOf('c'); 
var lastC=listWP.lastIndexOf('c-'); 

Content of array listWP is here (can't embed image)

Upvotes: 0

Views: 762

Answers (3)

MarsMan
MarsMan

Reputation: 13

I realized that indexOf() doesn't work for partial match.

Using .findIndex() would be great option for first match, but I also need the last one (element and index, so by reversing array I'd loose the index).

The working version is:

var allCs=listWP
              .map(function(element, index) { if(element.includes('c-')) {return index} })
              .filter(index => index != null);
  var firstC=allCs[0];
  var lastC=allCs[allCs.length-1];

Upvotes: 1

Kristkun
Kristkun

Reputation: 5953

Here's one option.

  1. filter your array first to get all strings with 'c-' prefix.

  2. Get the index of the first and the last filtered strings in your original array using indexOf()

Sample Code:

function getIndex(){
  var listWP = [ 'URG', 'c-I', 'c-II', 'c-II','c-III' ];
  //Filter array list with prefix 'c-'
  var filteredList = listWP.filter(function(str){return str.indexOf('c-') != -1;});
  Logger.log(filteredList);
  var firstC = listWP.indexOf(filteredList[0]);
  var lastC = listWP.indexOf(filteredList[filteredList.length - 1]);
  Logger.log(firstC);
  Logger.log(lastC);
}

Your code returns -1 since you are actually looking for 'c' and 'c-' in your array.

What the proposed solution does, is to filter first the array if it contains a specific string/char. Notice that I used indexOf() in a string to check if the prefix 'c-' exist in the string.

Upvotes: 1

Diego
Diego

Reputation: 9571

Since you're not looking for an exact match, you should use findIndex(). It will return the index of the first element that matches the condition.

const listWP = [ 'D1', 'c-I', 'URG' ];
const index = listWP.findIndex(item => item.startsWith('c'));
console.log(index);

Upvotes: 0

Related Questions