A method to find (an) item(s) in an array which inincludes specific character or strings

Hi,

Is there a method to find an element in an array that contains certain characters or strings? The following is a way of doing it, but I am curious if such a method already exists.

(
~itemStringInArrayFinder = { |array, which| var test, indices;
	test = array.collect { |item, index|
		if (item.asString.contains(which.asString)) { indices = indices.add(index) }; 
	};
	
	if (test.occurrencesOf(nil) == test.size) { nil } { indices }
}
)

~itemStringInArrayFinder.([\a, \bc, "cd" ], "c")
~itemStringInArrayFinder.([12, \1, "1d", 3 ], 1)

~itemStringInArrayFinder.([12, \1, "1d", 3 ], 3)
["one", "two", "three"].detectIndex(_.contains("two"));
["one", "two", "three"].detectIndex(_.contains(\two.asString));
1 Like

detectIndex only returns the first index, rather than a list of indices which match.

A closer approximation is:

~itemStringInArrayFinder = { |array, which|
	array.selectIndices { |x| x.asString.contains(which.asString) }
}

This returns [] instead of nil for no match, which is more idiomatic.

2 Likes

Thank you very much! Both methods are very useful! There is always something to learn.