i have an array that looks like this
let = ["1", "0", "0", "0", ".", "0", "0"]
i want to change the value of last index and then constantly move to the indexes of 0’s
for example i want to input 5,3,2. the output should become
updatedArray = ["1", "0", "0", "5", ".", "3", "2"]
is this possible?
i tried this to check for the indexes of 0
const stringValueArray = stringValue.split('');
const emptyStringIndices: number[] = [];
stringValueArray.forEach((element, index) => {
if (element === '0') {
emptyStringIndices.push(index);
}
});
const highestIndex = Math.max(...emptyStringIndices);
stringValueArray[highestIndex] = value;
const newValue = stringValueArray.join('');
return newValue;
2
Answers
New answer,
On second thought, if you
reverse
thedata
array, you canmap()
over it, returninput.pop()
if there is some (|| c
) as fallback, and then reverse it again.Original answer:
You can create a loop, in which you hold a flag for the last changed index.
Then check if that index is equal to
"0"
, if so, replace it with the last item in the changed array, usingpop()
so we can useinput.length
as thewhile
conditionKeep track of the original digits and the new digits entered. This is necessary, because you may need to enter 402 to get 1004.02, and you would not want the code to get confused and give 1000.42 as the result because it did not realise that the zero you entered needs to stay.
It is assumed that the input always contains the decimal place followed by two decimal numbers.
Then, get the result by combining the original digits with the entered digits, taking care to re-insert the decimal point before returning the result.
If too many digits are entered, ignore any excess digits.