0

I have an array like this

array: [
'Student 1|##|100|@@|Third answer', 
'Student 2|##|10|@@|Third Answer ',
'Student 10|##|50|@@|Third Answer'
]

In it 100 represents the id of the first item of the array, 10 represents the id of the second item of the array and 50 is the id of the third item and so on.

I also have a variable whose value is equal to the id which can be 100 or 10 or 50.

var id = data.myId

I need to check if the id exists in the array.

So if the id is 10 and I do array.includes(id.toString()) it won't return true unless my array is like:

array: [
   'Student 1|##|100|@@|Third answer', 
   'Student 2|##|10|@@|Third Answer ',
   'Student 10|##|50|@@|Third Answer',
   '10'
]

So how do I do that. I am guessing I have to use regex.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
DragonBorn
  • 1,809
  • 5
  • 20
  • 44

2 Answers2

3

I need to check if the id exists in the array.

Use some, split and check the 3rd item after splitting each item of the string item.

var has10 = array.some( s => s.split( "|" )[2] == "10" );

Demo

var array = [
  'Student 1|##|100|@@|Third answer',
  'Student 2|##|10|@@|Third Answer ',
  'Student 10|##|50|@@|Third Answer'
];
var id = "10";
var hasId = array.some( s => s.split( "|" )[2] == id );

console.log( hasId );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

You can use Array#.find() with this regex \|10\|:

let reg = new RegExp("\\|" + id + "\\|");

It will give you the first element matching the regex or an empty array if there's no match.

var array = [
  'Student 1|##|100|@@|Third answer',
  'Student 2|##|10|@@|Third Answer ',
  'Student 10|##|50|@@|Third Answer'
];
var id = 10;
let reg = new RegExp("\\|" + id + "\\|");
var result = array.find(function(item) {
  return item.match(reg);
});
console.log(result);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78