알고리즘 20 - A Needle in the Haystack

jabae·2021년 10월 17일
0

알고리즘

목록 보기
20/97

Q.

Can you find the needle in the haystack?

Write a function findNeedle() that takes an array full of junk but containing one "needle"

After your function finds the needle it should return a message (as a string) that says:

"found the needle at position " plus the index it found the needle, so:

findNeedle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk'])
should return "found the needle at position 5"

A)

function findNeedle(haystack) {
  
  for (let i = 0; i < haystack.length; i++) {
    if (haystack[i] === 'needle')
      return `found the needle at position ${i}`;
  }
  return 0;
}

other

아... 맞다 맞아.indexOf()가 있었지. 머리를 탁 치고 간다.🤦‍♀️

function findNeedle(haystack) {
  return "found the needle at position " + haystack.indexOf("needle");
}
profile
it's me!:)

0개의 댓글