0

I got some problem with this function Search program names that can be limited in the number of outputs that implement callback functions. hope you can help me figure out

function filteritem(str,num,callback){
  let result = name.filter( name => name.indexOf(str) !== -1 )
   result.forEach(element => element.length == num)
  callback(result);
}
function showFilter(wrd){
  console.log(wrd);
}
console.log(filteritem("a",3,showFilter))

My output is :

[
  'Abigail',  'Alexandra',
  'Amanda',   'Angela',
  'Bella',    'Carol',
  'Caroline', 'Carolyn',
  'Diana',    'Elizabeth',
  'Ella',     'Faith',
  'Olivia'
]
undefined

The output I want is :

["Abigail", "Alexandra", "Alison"];
0

2 Answers 2

1

const name = [
  "Abigail",
  "Alexandra",
  "Amanda",
  "Angela",
  "Bella",
  "Carol",
  "Caroline",
  "Carolyn",
  "Diana",
  "Elizabeth",
  "Ella",
  "Faith",
  "Olivia",
];
function filteritem(str, num, callback) {
  let result = name.filter((name) => name.indexOf(str) !== -1);
  result = result.slice(0, 3);
  callback(result);
}
function showFilter(wrd) {
  console.log(wrd);
}
filteritem("a", 3, showFilter);

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

Comments

0

What do you expect to achieve with your forEach call? You're iterating over the results array, and actually do nothing (your function returns a boolean: true if length == 3, false if not).

What you want to do is return the first 3 elements of result:

callback(result.slice(0, 3));

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.