0

I have 2 arrays containing string A and B. I want to find all the strings A matches with B. Let's say:

A = ['Battery mAh', 'Ram', 'Camera', 'Screen', 'Storage(GB)']
B = ['battery', 'ram', 'storage', 'Processor']

Output array should be follwoing:

output = ['Battery mAh', 'Ram', 'Storage(GB)']
1
  • I have tried 'includes' for exact match and 'match' for partial match. I just wanted to come up with faster and shorter solution. Commented Jul 19, 2020 at 10:32

3 Answers 3

3

You can filter A and check if it contains any element that B contains:

A.filter( // get only the elements that matches
     el => B.some( // check if there is any element in B that is contained in the current element of A
            obj => el.toLowerCase().includes(obj.toLowerCase())
     )
)

Returns:

["Battery mAh", "Ram", "Storage(GB)"]
Sign up to request clarification or add additional context in comments.

1 Comment

I'd use some instead of find for a boolean output, but that's personal preference.
0

That's a function doing that:

let items=[];

A.forEach(item => {
    for (let i=0; i<B.length; i++) {
        if (item.toLowerCase().includes(B[i]))
            items.push(item);
    }
});

return items;

Comments

0

You could convert array b into a regex, then filter array a based on whether or not a string matches this regex.

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
const escapeRegExp = string => string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');

const a = ['Battery mAh', 'Ram', 'Camera', 'Screen', 'Storage(GB)'];
const b = ['battery', 'ram', 'storage', 'Processor'];

const regex  = new RegExp(b.map(escapeRegExp).join("|"), "i");
const result = a.filter(product => product.match(regex));

console.log(result);

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.