Reputation: 483
I need to find the substrings within arrays.
If I have an array: ["abc", "abcd", "abcde", "xyz"]
, the method should return me the array members: "abc", "abcd", "abcde"
as each is a substring or a superstring of the other, but it should exclude "xyz".
What is the best possible method in javascript.
Upvotes: 1
Views: 87
Reputation: 386604
You could use some optimized loops with short cut and an object for the items.
var data = ["abc", "abcd", "42", "abcde", "422", "xyz", "q", "1q"],
result = function (array) {
var i, j,
r = {};
for (i = 0; i < array.length - 1; i++) {
if (r[array[i]]) {
continue;
}
for (j = i + 1; j < array.length; j++) {
if (r[array[j]]) {
continue;
}
if (array[i].indexOf(array[j]) !== -1 || array[j].indexOf(array[i]) !== -1) {
r[array[i]] = true;
r[array[j]] = true;
}
}
}
return array.filter(function (a) { return r[a]; });
}(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 36609
Use Array#filter
var arr = ["abc", "abcd", "abcde", "xyz"];
console.log(arr.filter(function(el) {
return el.indexOf('abc') > -1;
}));
Edit: Use Array#some
if you want to make filter based of some values in the array with respect to current element!
var arr = ["abc", "abcd", "abcde", "xyz"];
console.log(arr.filter(function(el, index) {
return arr.some(function(e, i) {
if (i !== index) {
return e.indexOf(el) > -1 || el.indexOf(e) > -1;
}
return false;
})
}));
Upvotes: 4
Reputation: 335
You can simply use 2 nested loops, but the complexity is O(n^2)
function find_substrings(arr) {
var res = [];
for (var i=0; i<arr.length; i++) {
for (var j=0; j<arr.length; j++) {
if (i !== j && (arr[i].indexOf(arr[j]) > -1 || arr[j].indexOf(arr[i]) > -1)) {
res.push(arr[i]);
break;
}
}
}
return res;
}
var arr = ["abc", "abcd", "abcde", "xyz"];
console.log(find_substrings(arr));
Upvotes: 1