How to loop through numeric values (numbers) in JavaScript? - javascript

Let's say I have a variable like this:
const numbers = 1234567654321;
How do I loop through each number here?
I'm so mad I can't find an answer on google for such an easy subject.
Here's what I've been trying to do:
const numbers = 1234567654321;
const str = numbers.toString();
let results = [];
for (let i = 0; i <= str.length; i++) {
results.push(+str[i]);
}
console.log(results);

Your code works correctly. There's only one problem which is the loop condition which should be i < str.length
const numbers = 1234567654321;
const str = numbers.toString();
let results = [];
for (let i = 0; i < str.length; i++) {
results.push(+str[i]);
}
console.log(results)

Your own answer seems to work (except for the wrong index, like mentioned by Rifat Bin Reza).
You could also use split() instead of the for-loop:
const numbers = 1234567890;
const result = numbers.toString().split('').map(num => parseInt(num));
console.log(result);

Your code is fine, except for cheking condition i<= str.length should be i < str.length.
Another approach using map().
const number = 12345;
const solution = [...`${number}`].map(number => +number);
console.log(solution);

Related

Why is my nested loop only finding one duplicate character in a string?

My apologies if this is a duplicate, I couldn't find an answer after searching for a while on Stackoverflow.
I am trying to use a nested loop to find any duplicate characters in a string.
So far, all I can manage to do is to find one duplicate the string.
For example, when I try the string "aabbcde", the function returns ['a', 'a'], whereas I was expecting ['a', 'a', 'b', 'b'].
I obviously have an error in my code, can anybody help point me towards what it could be?
const myStr = "aabbcde";
function duplicateCount(text){
const duplicates = [];
for (let i = 0; i < text.length; i++) {
for (let j = 0; j < text[i].length; j++) {
if (text[i] === text[j]) {
duplicates.push(text[i]);
}
}
}
return duplicates;
}
duplicateCount(myStr);
It should be something like this.
issues in this loop for (let j = 0; j < text[i].length; j++)
const myStr = "aabbcde";
function duplicateCount(text){
const duplicates = [];
for (let i = 0; i < text.length; i++) {
for (let j = i+1; j < text.length; j++) {
if (text[i] === text[j]) {
duplicates.push(text[i]);
}
}
}
return duplicates;
}
console.log(duplicateCount(myStr));
Using nested loop will make it very hard to do it,we can use a Object to store the appear count,and then filter the count
const myStr1 = "aabbcde";
const myStr2 = "ffeddbaa";
const duplicateCount = str => {
let map = {}
for(c of str){
map[c] = (map[c]??0) + 1
}
let result = []
for(m in map){
if(map[m] <= 1){
continue
}
result.push(...Array(map[m]).fill(m))
}
return result
}
console.log(duplicateCount(myStr1))
console.log(duplicateCount(myStr2))
You can simply achieve the result you're looking for by creating an object map of the string (meaning each key of the object will be each unique character of the string and their associated values will be the number of times each character is repeated in the string).
After you create an object map of the string, you can loop through the object and check if each value is greater than one or not. If they're you would push that item into a result array by the number of times the character is repeated. Please find my code here:
const myStr = 'aabbcde';
const duplicateCount = (str) => {
const result = [];
const obj = {};
str.split('').map((char) => {
obj[char] = obj[char] + 1 || 1;
});
for (key in obj) {
if (obj[key] > 1) {
for (let i = 0; i < obj[key]; i++) {
result.push(key);
}
}
}
return result;
};
console.log(duplicateCount(myStr));

javascript variable not changed

I'm trying to do a little program to reverse a string and I'm using this approch:
var reverse = (str) => {
let returned = [...str];
for(let i = 0; i < returned.length; i++)
{
let symetrical = returned.length - i - 1;
let temp = returned[i];
returned[i] = returned[symetrical];
returned[symetrical] = temp;
}
return returned.join("");
}
but when i test the function like reverse('123') I got the same input as result?
why the returned variable didn't change?
You can simplify the function by creating two arrays, the array of the letters of the param str, and the results array which takes the length - 1 - i algorithm you had:
let reverse = (str) => {
const arr1 = [...str];
const arr2 = []
for(let i = 0; i < arr1.length; i++)
{
arr2[i] = arr1[arr1.length - 1 - i];
}
return arr2.join("");
}
console.log(reverse("abcde"));

Leetcode problem: Remove Duplicates from Sorted Array

Example :
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums
being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
My code to solve this problem is
var removeDuplicates = function(nums) {
const non_duplicates = [];
for (let i=0;i<=nums.length-1;i++){
if(!(non_duplicates.includes(nums[i]))){
non_duplicates.push(nums[i]);
}
}
console.log(non_duplicates)
return non_duplicates.length;
};
That console.log(non_duplicates) displays correct output in stdOut. But when I return non_duplictes it prints empty array in output. And when I return non_duplictes.length it returns some array rather than the length of that array.
Please don't suggest any other method to solve this problem. Just tell what is wrong with this code
You can see that problem here
Your solution doesn't modify the array inplace. That's the first problem.
A bigger problem is that your algorithm is with O(N^2) time complexity, due to includes call and given that "1 <= nums.length <= 3 * 104" your solution would be incredibly slow if it ever passes the tests.
The goal is to find a linear solution of the problem. One possible solution would be:
var removeDuplicates = function(nums) {
let j = 0;
for (let i = 1, len = nums.length; i < len; i++) {
if (nums[i] !== nums[j]) {
nums[++j] = nums[i];
}
}
return j + 1;
};
You can achieve that by using Set() Object.
let nums = [0,0,1,1,1,2,2,3,3,4];
const uniqueNums = [...new Set(nums)];
console.log(uniqueNums.length, uniqueNums);
You're returning the correct value but you are not overwriting the nums array with the non-duplicate values.
After calling your function, the return value should be 5 and the first 5 values in the passed-in nums array should be 0,1,2,3,4 (the value of the others doesn't matter).
Simplest solution that's compatible with your attempted solution is:
copy the values from non_duplicates into nums
return non_duplicates.length.
Here's a simple example of how to do this:
var removeDuplicates = function (nums) {
const non_duplicates = [];
for (let i = 0; i < nums.length; i++) {
if (!non_duplicates.includes(nums[i])) {
non_duplicates.push(nums[i]);
}
}
for (let i = 0; i < non_duplicates.length; i++) {
nums[i] = non_duplicates[i];
}
return non_duplicates.length;
};
Note: this is not the most efficient solution, and efficiency becomes important with the medium to hard Leetcode challenges, but it's simple, close to your intended solution, and it works.

.join is not a function

Newer to coding and javascript and I am trying a codewars challenge. I setup an array to repeat a letter at certain indexes of my newArray based on a loop. For example if input was: cwAt expected output should be: C-Ww-Aaa-Tttt.
Been stuck on this for several hours (and have slept on it). I get error code:
newArray.join is not a function
when I try to run this and not sure what I can do to fix this problem. I feel its something simple and I just need to learn why this is happening.
function accum(s) {
let mumble = s.split('');
for (i = 0; i < mumble.length; i++) {
let newArray = [mumble[i].toUpperCase(), ''];
for (j = i; j > 0; j--) {
newArray = newArray.push(mumble[i]);
};
// Merge the new array into a string and set it at the mumble index required
mumble[i] = newArray.join('');
};
//Return new mumble with - as spaces between elements
return mumble.join('-');
}
console.log(accum('cwAt'));
Change newArray = newArray.push(mumble[i]); to newArray.push(mumble[i]);
push returns new length of the array.
You are storing a number in newArray. Try replace the 4 line with:
let newArray[i] = [mumble[i].toUpperCase(), ''];
and the 5 line :
for (j = 0; j < 0; j++) {
and the 6:
newArray[j] = newArray.push(mumble[i]);

How to use array of regex pattern to check the url

I have array of regex pattern, i want to check the url which matches the regex and use it.
please let me know the best way to do it.
The code i have written is something like this.
var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = a.exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
Expected:
when i use a.exec it should parse the url "/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"
and give results.
Iterate over the regexes like this:
var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = [];
for (var i = 0; i < a.length; i++) {
result.push(RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"));
}
All matches are then stored in result.
result[0] is a array with matches from the regex in a at index 0, result[1] --> a[1], etc. If there are no results from the regex, result[x] will be null.
Instead of pushing the regex result to a array, you could also work on the result directly:
for (var i = 0; i < a.length; i++) {
var currentResult = RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
// Do stuff with currentResult here.
}
You can loop over your regex array:
var a = [/^\/(.*)\/product_(.*)/, /(.*)cat_(.*)/];
var results = [];
for (var i = 0; i < a.length; i++) {
var result = a[i].exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
results.push(result);
}
console.log(results);

Categories

Resources