-1

Hello everyone I struggling to create an expression to check if a specific array includes only a specified type values.Here is what I tried :

const isArrayOfType = (arr, type) =>
  arr.forEach((item) => typeof item == type) ? true : false;

const arr = [1, 2, 3];
const typ = 'number';

console.log(isArrayOfType(arr, typ));

The main goal is to not use return in the expression.

1 Answer 1

2

forEach doesnt return anything, I think you're looking for every (and the ternary operator is unecessary as it already returns a boolean)

const isArrayOfType = (arr, type) =>
  arr.every((item) => typeof item == type);

const arr = [1, 2, 3];
const typ = 'number';

console.log(isArrayOfType(arr, typ));
console.log(isArrayOfType(["one",2,3], typ));

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

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.