Middle
There is an array of objects with a 'value' field. How to create a new array containing only the numeric values from these objects (excluding strings)? How to do this and how to check if a value is a number?
sobes.tech AI
Answer from AI
To obtain a new array containing only the numeric values of the value field from an array of objects, you can use the filter and map methods in JavaScript.
You can check if a value is a number using the typeof function and by checking for NaN:
const arr = [
{ value: 10 },
{ value: '20' },
{ value: 30 },
{ value: 'abc' },
{ value: 40 }
];
const numbers = arr
.map(obj => obj.value)
.filter(val => typeof val === 'number' && !isNaN(val));
console.log(numbers); // [10, 30, 40]
Here:
mapextracts thevaluefield from each object.filterkeeps only those values that are of typenumberand are notNaN.
If you also want to consider numeric strings, you can use Number and check the result:
const numbers = arr
.map(obj => Number(obj.value))
.filter(val => !isNaN(val));
But since the question specifies without strings, the first option is suitable.