-1

I had a problem with array like this. First, I have an array and a string and I must compare this array and this string. If this array has an element the same as the element of the string, I must create a new array which has this element. For example :

mang : ['Javascript', 'PHP', 'H PHP']

chuoi = "PHP"

When we compared "chuoi" and "mang", as you can see, we have "PHP", so I must create the array ['PHP']

here is my code (my idea)

function findStringsInArrayByKeyword(keyword, strings) {
var chuoi = "PHP";
var mang = ['Javascript', 'PHP', 'Học PHP'];
mang.forEach(function(a)){
if (a===chuoi) {
     return [a];
}
}
}

But it still does not run, could you please give me some ideas for me? Thank you very much for your time.

1 Answers1

0

forEach does not return any value. In this case you can use reduce

function findStringsInArrayByKeyword(keyword, strings) {
  var chuoi = "PHP";
  var mang = ['Javascript', 'PHP', 'Học PHP'];
  return mang.reduce((acc, curr) => {
    if (curr === chuoi) {
      acc.push(curr);
    }
    return acc;
  }, [])
}

console.log(findStringsInArrayByKeyword())
brk
  • 48,835
  • 10
  • 56
  • 78