Lim SY Lim SY - 4 months ago 16
Javascript Question

Searching and filtering array

Lets say I have an array like this:

var arr = ['hello, my', 'hello, my name is', 'hello, my name is newton', 'hello, his', 'hello, his name is', 'hello, his name is pluto', 'hello, she is britney'];


I want to filter it into:

var arr = ['hello, my name is newton', 'hello, his name is pluto', 'hello, she is britney'];


I don't know how to put this but the condition is like if an array element's string can be found on other element then it should be removed. Like 'hello, my' can be found exactly in the next following element 'hello, my name is' so 'hello, my' should be removed.

The actual array I'm trying to filter is:

var arr = ['11 22 13', '11 22 13 34', '11 22 13 34 15', '11 22 13 34 35', '11 22 23', '11 22 23 34', '11 22 23 34 15', '11 22 23 34 35', '31 22 13', '31 22 13 34', '31 22 13 34 15', '31 22 13 34 35', '31 22 23', '31 22 23 34', '31 22 23 34 15', '31 22 23 34 35'];


I've tried to break it into different groups but I still do not know what to do with it. I'll show it anyway:

var threelink = [];
var fourlink = [];
var fivelink = [];

for(var i=0; i < arr.length; i++){
if(arr[i].length>8&&arr[i].length<12){
fourlink.push(arr[i]);
}
else if(arr[i].length>11){
fivelink.push(arr[i]);
}
else {
threelink.push(arr[i]);
}
}

Answer

How about this?

var arr = ['11 22 13', '11 22 13 34', '11 22 13 34 15', '11 22 13 34 35', '11 22 23', '11 22 23 34', '11 22 23 34 15', '11 22 23 34 35', '31 22 13', '31 22 13 34', '31 22 13 34 15', '31 22 13 34 35', '31 22 23', '31 22 23 34', '31 22 23 34 15', '31 22 23 34 35'];

arr.sort();
var filterArray = new Array();
for(var i = 0 ; i < arr.length; i++) {
    if(i + 1 == arr.length) {
    filterArray.push(arr[i]);
  } else {
    if(arr[i+1].startsWith(arr[i])) {
        continue;
    } else {
        filterArray.push(arr[i]);
    }
  }
}
alert(filterArray);

JSFiddle