I have the following string
"0,2,4,5,6"
how can check if these numbers are in array
let daysweek = [
{ id: '0', name: 'Domingo' },
{ id: '1', name: 'Segunda' },
{ id: '2', name: 'Terça' },
];
Create a set of the ids in daysofweek
, allowing you to easily check if an id is in daysweek
.
let daysweek = [
{ id: '0', name: 'Domingo' },
{ id: '1', name: 'Segunda' },
{ id: '2', name: 'Terça' },
];
let days = "0,2,4,5,6";
let set = new Set(daysweek.map( _ => _.id ))
let found_days = days.split(",").filter( day => set.has(day) );
console.log(found_days);
This is O(N). AlwaysHelping's answer and MarkCBall's answers are O(N 2 ), which will fare far more poorly as the number of items in daysweek
increases.
You can simply use Array#map and split function to do that.
Split()
will remove all commas
from your string
and convert it an array
.
And using map
we get all the id's with and store them in a variable
and check using Array#forEach which id's matched with string
you have.
Live Demo:
let daysweek = [{ id: '0', name: 'Domingo' }, { id: '1', name: 'Segunda' }, { id: '2', name: 'Terça' }, ]; let str = "0,2,4,5,6".split(',') //split the string let daysID = daysweek.map(y => y.id) //store the id's str.forEach(function(x){ let found = daysID.includes(x) console.log(x + " = " +found) //show true or false for each found id })
let daysweek = [
{ id: '0', name: 'Domingo' },
{ id: '1', name: 'Segunda' },
{ id: '2', name: 'Terça' },
];
const daysWeekIds = daysweek.map(obj=>obj.id)
const numbersAreInArray = "0,2,4,5,6".split(",").every(num=>daysWeekIds.includes(num))
console.log(numbersAreInArray)
I would like to thank you all, I found a example that met my need
daysweek2 = [
'Domingo',
'Segunda',
'Terça',
'Quarta',
'Quinta',
'Sexta',
'Sábado',
];
function initDays() {
return "0,2,4".split(',')
.map(key => this.daysweek2[key]).join(',').split(',')
}
console.log(this.initDays());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.