Reputation: 51
I'm coding something in extendscript for adobe after effects, which ends up being javascript.
I have an array and I would like to do a search for just the word "assemble" and return the whole jc3_RIG_008_masterLayer assemble string
var comps = ["_MAIN", "jc3_RIG_008_masterLayer assemble","jc3_RIG_008_masterLayer contact sheet", "[Z] source", "MM004 source"];
I'm not sure what the best/ most efficient way to achieve this is, but any thoughts would help.
Thanks.
Upvotes: 2
Views: 157
Reputation: 6271
A normal for-loop should do the trick. This is the fastest way according to some sources. Also using indexOf()
is faster than using search()
according to other sources:
for (var i = 0, len = comps.length; i < len ; i++) {
if (comps[i].indexOf('assemble') > -1) return comps[i]; //or store and break
}
var comps = ["_MAIN", "jc3_RIG_008_masterLayer assemble","jc3_RIG_008_masterLayer contact sheet", "[Z] source", "MM004 source"];
comps.forEach(function(el) {
if (el.indexOf('assemble') > -1) document.write('loop 1: ' + el + '<br>');
});
for (var i = 0, len = comps.length; i < len ; i++) {
if (comps[i].indexOf('assemble') > -1) document.write('loop 2: ' + comps[i]);
}
<div id="output"></div>
I'll keep this here as reference:
Something like this would work for anything with ECMAScript5 support (but according to sources, and @frxstrem, this is not available in ExtendedScript):
comps.forEach(function(el) {
if (el.indexOf('assemble') > -1) return el;
});
Upvotes: 1
Reputation: 251
@josegomezr has the right idea using a simple loop. I updated that idea to return the string that the poster is looking for.
var comps = ["_MAIN", "jc3_RIG_008_masterLayer assemble","jc3_RIG_008_masterLayer contact sheet", "[Z] source", "MM004 source"];
var compWithAssemble;
for(var i in comps){
if(comps[i].indexOf("assemble") > -1){
compWithAssemble = comps[i];
break;
}
}
// compWithAssemble has the string you are looking for.
console.log(compWithAssemble);
Upvotes: 2
Reputation: 916
If it is plain JS you can do this:
var found = false;
for(var i in comps){
if(comps[i].search("assemble") != -1){
found = true;
break;
}
}
if(found){
// your code if found
}else{
// your code if not.
}
Upvotes: 0