Find Number in Array (two-digit Number)

Viewed 464

I try to find the Number 7 in an Array and return true (Doesn´t matter if it´s 7, 47 or 507)

The Array: [17, 23, 9, 590]

I tried to use arr.includes(7) but this just returns the Number 7. (So it returns false in this case because there is no 7 in the Array - only 17)

5 Answers

The problem is the comparison number === 7, you should compare each digit instead.

You can use the function Array.prototype.some, and the function String.prototype.includes to check for a specific digit/char.

This approach finds the number 7 over each number's digit.

console.log([17, 23, 9, 590].some(n => String(n).includes(7)))

You could join the numbers and look if 7 is included.

var data = [17, 23, 9, 590],
    has7 = data.join('').includes(7);

console.log(has7);

Wouldn't you mod the number by 10 and then look for 7?

const findByLeastSigFig = (arr, n) => arr.find(x => x % 10 === n);

console.log(findByLeastSigFig([17, 23, 9, 590], 7));

Assuming that the 7 is only valid in the last position you could use the rest of division by 10

const elements = [7, 9, 17, 23, 57, 407, 590];
const result = elements.filter(element => element % 10 === 7)
console.log(result)

There is more than one correct answer to this problem. One of the simplest and most intuitive ones (without compromising on performance) is to use Array.prototype.toString() which joins the array and returns one string containing each array element separated by commas. [17, 23, 9, 590].toString() returns the string "17,23,9,590" and then look for the index of 7 using String.prototype.indexOf() which returns the 0-based index of the serach value or -1 if not found.

To sum it up in one line:

console.log([17, 23, 9, 590].toString().indexOf(7) != -1);

Related