user1592380
user1592380

Reputation: 36247

How to get indexes of specific array elements in Apps script

Using apps script I have:

var conversation = [R: test1 ,  R: test3 ,  tx ,  I sent ]

I wanted to get a list of the INDEXES of elements containing 'R:' so I tried

var replies = conversation.map(function(message) { 
    message.indexOf('R:')!== -1 && return conversation.indexOf(message);

});  

But now I can't save the function and I'm getting a syntax error. What am I doing wrong?

Upvotes: 0

Views: 1392

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

Two things:

  1. You can't do this with just map.
  2. You have your return in the wrong place, which is the cause of the syntax error.

To do it in a single pass, the simplest thing is to use forEach and push (since Apps script doesn't support for-of):

var replies = [];
conversation.forEach(function(message, index) {
    if (message.indexOf("R:") !== -1) {
        replies.push(index);
    }
});

but you could do it in two passes with map and filter:

var replies = conversation
    .map(function(message, index) {
        return message.indexOf("R:") !== -1 ? index : -1;
    })
    .filter(function(index) {
        return index !== -1;
    });

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You can use reduce and keep pushing indexes where you find R:

var conversations = ['R: test1' ,'R: test3','tx','I sent' ]

var replies = conversations.reduce(function(op,message,index) {
    if(message.indexOf('R:')!== -1) {
      op.push(index)
    }
    return op
},[]);  

console.log(replies)

Upvotes: 2

Related Questions