I am trying to create a method that removes all the zeros from a string (a string that contains numbers) for each element of an array;
I get this error 'type void is not assignable to programs[]
public removeLeadingZeros(programs: Program[]) {
let programCopy: Program[];
programCopy= programs.forEach(p => {
p.number.replace(/^0+/, '');
});
return programCopy;
}
As an alternative to the other answer, instead of using .forEach()
which doesn't return anything, you can use the .map()
which returns an array of what you have changed.
let programCopy: Program[];
programCopy = programs.map(p => {
p.number.replace(/^0+/, '');
return p;
});
EDIT: Here is the shorter version of this code
let programCopy: Program[] = programs.map(p => p.number.replace(/^0+/, ''));
Thats because forEach does not have any return type.
if you want to store the objects with the replaced numbers in programCopy just copy the programs parameter and change them:
programCopy = programs;
programCopy.forEach(p => {
p.number.replace(/^0+/, '');
});
Use the following instead of forEach loop:
programCopy = programs.filter(p => p !== 0);
You can use filter method. It returns an array of the filtered items. Now, the programCopy variable contains the number without zeros.
You can use this approach.
public removeLeadingZeros(programs: Program[]) { let programCopy: Program[]; programs.forEach(p => { programCopy.push(p.number.replace(/^0+/, '')) }); return programCopy; }
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.