Home > Enterprise >  Determine the type of array as boolean result
Determine the type of array as boolean result

Time:12-30

I could not find exact answer for my problem, just want a way to determine something like

const numArray = [1,2,3,4];
const objArray = [{thing: value}, {thing: value}];

if (numArray typeof number[]) { console.log('This is an array of numbers.') }
if (objArray typeof object[]) { console.log('This is an array of objects.') }

Hope this explains even though I know is not correct as I am just learning.

CodePudding user response:

You can check the type of the first item of the array and assume that all items have the same type:

const numArray = [1,2,3,4];
const objArray = [{thing: 'value'}, {thing: 'value'}];

if (typeof numArray[0] === 'number') {
  console.log('This is an array of numbers.');
}

Or you can use Array.every() to check all of them:

if (objArray.every((item) => typeof item === 'object')) {
  console.log('This is an array of objects.');
}

CodePudding user response:

Use typeof to create a condition and use it with Array.every()

const isNumeric = (currentValue) => typeof currentValue == 'number';

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isNumeric));
// expected output: true

CodePudding user response:

An easy way to do it would be to use the every method of Arrays.

tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. — MDN docs

We can check whether the condition in the callback to Array.every is satisfied for every element, that is whether every element is of the specified type.

/**
 * @function allOfType
 * @description - checks whether all elements in an array are of the specified
 * type
 * @param {Array} array - array to check in
 * @param {String} type - type to check for
 * @return {Boolean}  whether all elements are of specified type
 */
function allOfType(array, type) {
  return array.every((v) => typeof v === type);
}

console.log(allOfType(numArray, 'number'));
console.log(allOfType(objArray, 'object'));

CodePudding user response:

Try this:

  • array of number : numArray.every(i=> typeof i == 'number')
  • array of object: numArray.every(i=> typeof i == 'object')
  • Related