0

I have arr with categories tree. Example: category yy is subcategory of ww and ww is subcategory of zz. I want to filter this array and get this output: ['aa_bb', 'aa_cc', 'zz_ww_yy']. So I don't want zz and zz_ww becouse i have this in zz_ww_yy. I think that I must use filter function and maybe some regexp? hmmm and maybe foreach? What you think?

var arr = ['aa_bb', 'aa_cc', 'aa', 'zz', 'zz_ww','zz_ww_yy'];

var filtered = arr.filter(function(a){
    //???
})

console.log(filtered);
1
  • Welcome to Stack Overflow! Please take the tour and read through the help center, in particular How do I ask a good question? Do your research, search for related topics on SO, and give it a go. (You're likely to need two passes through the array, and regex probably isn't much help here.) If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! Commented Dec 31, 2017 at 12:26

2 Answers 2

2

You could take String#indexOf and filter the temporary result array with the given string.

Then check if the string is not a substring of the result set and push it if not.

var array = ['aa_bb', 'aa_cc', 'aa', 'zz', 'zz_ww','zz_ww_yy'],
    result = array.reduce(function (r, a) {
        r = r.filter(b => a.indexOf(b) === -1);
        if (r.every(b => b.indexOf(a) === -1)) {
            r.push(a);
        }
        return r;
    }, []);
    
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

try that on also, you could easely change the logic.

var arr = ['aa_bb', 'aa_cc', 'aa', 'zz', 'zz_ww', 'zz_ww_yy'];

function shoulFilterCategory(arr, itemToTest, itemIndex) {
  var shouldFilter = false;

  arr.filter((item, index) => index !== itemIndex)
     .forEach(item => {
    if (item.startsWith(itemToTest) && itemToTest.length < item.length)         {
      shouldFilter = true;
    }
  });
  return shouldFilter;
}

var filtered = arr.filter(
  (item, index) => !shoulFilterCategory(arr, item, index)
);

console.log('filtered', filtered);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.