Get first element of array if is a string number

Fabrizio Joaqui
Mega Guru

Hi all, I have this array of objects, and i have to take the first object that have property 'userId' as a number

For example i want to take object {name: 'Mario',userId: '040287960321'}

to do this I would like to do a while-loop and use regex, so that it returns me the first object that passes the regex test, but I don't know how to do it.

Other solutions are welcome.

var arr2 = [
  {
  name: 'Luke',
  userId: 'Test'
  },
  {
    name: 'Mario',
    userId: '040287960321'
  },
  {
  name: 'George',
  userId: 'test_1'
  }
  
]
1 ACCEPTED SOLUTION

AnirudhKumar
Mega Sage
Mega Sage

Here's the script, used for loop ... simpler

var arr2 = [
  {
  name: 'Luke',
  userId: 'Test'
  },
  {
    name: 'Mario',
    userId: '040287960321'
  },
  {
  name: 'George',
  userId: 'test_1'
  }
  
];


var numericalUserIdObj = [];
for(var i = 0;i<arr2.length;i++)
{
if(isNaN(arr2[i].userId) == false)
numericalUserIdObj.push(arr2[i]);
}

gs.info(numericalUserIdObj + '  ' + numericalUserIdObj[0].userId);

View solution in original post

4 REPLIES 4

AnirudhKumar
Mega Sage
Mega Sage

Here's the script, used for loop ... simpler

var arr2 = [
  {
  name: 'Luke',
  userId: 'Test'
  },
  {
    name: 'Mario',
    userId: '040287960321'
  },
  {
  name: 'George',
  userId: 'test_1'
  }
  
];


var numericalUserIdObj = [];
for(var i = 0;i<arr2.length;i++)
{
if(isNaN(arr2[i].userId) == false)
numericalUserIdObj.push(arr2[i]);
}

gs.info(numericalUserIdObj + '  ' + numericalUserIdObj[0].userId);

thanks 

AnirudhKumar, 
 
but return me the last element, i want the first element.
 
for example if i add other object: 
var arr2 = [
  {
  name: 'Luca',
  userId: 'Test'
  },
  {
    name: 'Mario',
    userId: '040287960321'
  },
  {
    name: 'Michele',
    userId: '040287960327'
  },
  {
  name: 'Giorgio',
  userId: 'test_1'
  }
  
]

return me {name: 'Michele', userId: '040287960327'}

AnirudhKumar
Mega Sage
Mega Sage

If you'd like just the object rather than the array, here's the modified code:

var arr2 = [
  {
  name: 'Luke',
  userId: 'Test'
  },
  {
    name: 'Mario',
    userId: '040287960321'
  },
  {
  name: 'George',
  userId: 'test_1'
  }
  
];


var numericalUserIdObj = {};
for(var i = 0;i<arr2.length;i++)
{
if(isNaN(arr2[i].userId) == false)
{
numericalUserIdObj.name = arr2[i].name;
numericalUserIdObj.userId = arr2[i].userId;
}
}

gs.info(numericalUserIdObj + '  ' + numericalUserIdObj.userId);

John Dewhurst
Kilo Guru

In ES6+ (Scoped in Tokyo) you could do it like this...

let user = arr2.find((user) => /^\d+$/.test(user.userId));

Otherwise it would be like...

function getUser(arr){
  for(var i = 0; i < arr.length; i++)
    if(/^\d+$/.test(arr[i].userId))
      return arr[i];
}
var user = getUser(arr2);