Convert number to a reversed array of digits - javascript

I've developed this codepen (http://codepen.io/PiotrBerebecki/pen/qZjojV?editors=0010) trying to solve the following JavaScript problem:
Given a non-negative integer, return an array containing a list of independent digits in reverse order.
Example:
348597 => The correct solution should be [7,9,5,8,4,3]
The function below apparently is incorrect as it returns ["7", "9", "5", "8", "4", "3"] - correct order but with quotes. How could I modify it so that it returns [7,9,5,8,4,3]?
function digitize(n) {
var initialArray = (""+n).split('');
var reversedArray = [];
for (var i = initialArray.length - 1; i >= 0; i--) {
reversedArray[i] = initialArray.shift();
}
return reversedArray;
}

"One-line" solution:
var num = 348597,
arr = String(num).split("").reverse().map(Number);
console.log(arr); // [7, 9, 5, 8, 4, 3]
String(num) : The String global object acts as a constructor for strings and "converts" the given number into string(in this case)
The Array.reverse(): method reverses an array in place
The Array.map(): method creates and returns a new array calling a provided function on every array element

add parseInt to convert from string to number, since when you split you turn every integer into a string
function digitize(n) {
var initialArray = (""+n).split('');
var reversedArray = [];
for (var i = initialArray.length - 1; i >= 0; i--) {
reversedArray[i] = parseInt(initialArray.shift(),10);
}
return reversedArray;
}
console.log(digitize(348597));

Even better, reduce it to two lines:
function digitize(num) {
return num.toString().split('').reverse().map(Number);
}
The final map call applies a function to each element in the array (in this case the function converts a string to an object) - everything else simply converts the number to a string, splits the string to an array and reverses it.
Traditionally, parseInt would be used in the map call, but this gives rise to strange behaviour.

Just split and reverse
var num = 348597,
arr = num.toString().split("").reverse().map(Number);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');

It is a simplified version of many other solutions that you can see, to deep understand how it works.
function digitize(n) {
let correctArr = [];
let arrOfNumbers = n.toString().split('');
let arrOfNumbersLength = arrOfNumbers.length;
for (let i = 0; i < arrOfNumbersLength; i++) {
let x = arrOfNumbers.pop();
correctArr.push(+x);
}
return correctArr;
}
console.log(digitize(348597));

If you care about performance, here is the one.
var num = 348597;
var digits = num + '';
var result = [];
for (var i = 0, length = digits.length; i < length; i++) {
result[length - 1 - i] = +digits[i];
}
console.log(result);

For beginners who may want to see a clear format on how to solve this via plain English, this may help to understand it:
function reverseNumber(num){
num = num + '';
let reversedText = num.split('').reverse().join('');
let reversedNumber = parseInt(reversedText, 10);
console.log("reversed number: ", reversedNumber);
return reversedNumber;
}
console.log(reverseNumber(12345));

A simpler way to solve this is below.
function digitize(n) {
numbers = n.toString()//convert n to a string
arrayNum = numbers.split('') //split the string and make an array
arrayRev =arrayNum.reverse()//reverse the new array made.
newArr = arrayRev.map(Number) // The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.
return newArr;
}
Refactored
function digitize(n) {
return n.toString().split('').reverse().map(Number)
}

Related

Scramble String According to Array Values - Javascript

Trying to solve this question on Codewars.
I've seen other articles that deal with shuffling / scrambling a string randomly.
But what about scrambling a string according to the values in a given array?
I.e. abcd given the array [0, 3, 2, 1] will become acdb because:
a moves to index 0
b moves to index 3
c moves to index 2
d moves to index 1
My guess is to start out by splitting the string into an array. And then we want to get the index value of the array that's passed into the scramble function, and push the character at the index value from that array into the new array. And finally join the array:
function scramble(str, arr) {
let newArray = str.split("");
let finalArray = [];
for (let i = 0; i < str.length; i++) {
console.log(newArray);
finalArray.push(newArray.splice(arr[i], 1));
}
return finalArray;
}
console.log(scramble("abcd", [0, 3, 1, 2]));
But the problem with this logic is that .splice() removes the character from the newArray every time.
Is there another method that will remove the character at the specified index without modifying the original array?
I don't think slice will work either.
You can make a separate array to store the letters.
var str = "abcd";
var arr = [0, 3, 2, 1];
function scramble(s, a) {
var ar = Array(a.length);
a.forEach((e, i) => {
ar[e] = s[i];
});
return ar.join('');
}
console.log(scramble(str, arr));
Answer
Use reduce on the array and as the array is iterated assign the character of the iterator index(i) in the string(s) to the value index(v) of the new array(ra). After the reduce completes, use join to turn the returned array(ra) back into a string.
let scramble = (s, a) => a.reduce((ra,v,i)=> (ra[v] = s[i], ra), []).join("");
Example:
let scramble = (s, a) => a.reduce((ra,v,i)=> (ra[v] = s[i], ra), []).join("");
console.log( scramble("abcd", [0,3,2,1]) );
Clarification Code:
I realize the above code may be hard to wrap your head around. Let me provide you with the same exact functionality, but in a standard function. Keep in mind this is exactly what is happening in the above code, but it may be simpler to comprehend if you're not used to the concision of ES6:
function scramble(my_string, my_array) {
// create an array to return
let returnable_array = [];
// loop through the provided array.
// string index is the array key: 0,1,2,3
// array_index is the value of the array keys: 0,3,2,1
for(let [string_index, array_index] of my_array.entries()) {
// we assign the character at string index
// to the value index inside the returnable array
returnable_array[array_index] = my_string[string_index];
}
// we turn the array into a string
let returnable_string = returnable_array.join("");
// we return the string
return returnable_string
}
Example:
function scramble(my_string, my_array) {
let returnable_array = [];
for(let [string_index, array_index] of my_array.entries()) {
returnable_array[array_index] = my_string[string_index];
}
returnable_string = returnable_array.join("");
return returnable_string
}
console.log(scramble("abcd", [0,3,1,2]));
You can loop over the input string get the character at the current position using string.charAt(position) and put it into a new array into the position retrieved from the positions array.
function scramble (str, arr) {
let newArray = [];
for (let i = 0; i < str.length; i++) {
newArray[arr[i]]=str.charAt(i);
}
return newArray.join();
}
console.log(scramble("abcd", [0, 3, 1, 2]));
I think the best approach would be to put the string into a new array:
function scramble(str, arr) {
//validate if the array has elements
if (arr && arr.length) {
//create a new array
const strArr = []
arr.forEach(index => {
//push each character by index
//As noted by Barmar you could either use
//str.charAt(index) or str[index]
//as both will return the character at the specified index
strArr.push(str.charAt(index))
})
//return a new string
return strArr.join('');
}
}

how to increment interger array by 1

I have an array like so [1,9,9,9,9,9]. I want to increment this array by one and return [2,0,0,0,0,0]. Here's the catch - you can't join() or concat(). You cannot change the array in any way other than adding to it. However, you can reverse it but I'm not sure how much that would help
Also, here are a few other examples;
[1,8,9] => [1,9,0];
[1,2,3,9,1] => [1,2,3,9,2];
[5,7,9,9] => [5,8,0,0];
The result can only return an array with single digits.
Basically, pretend that the array is a single number and you're adding 1 to it. Again, no joining, splitting, turning into a string.. etc.
Ideally, I would like a classic loop solution or possibly a recursion solution. Thank you!
here is my repl.it https://repl.it/#CharChar5/Code-Challenge
Thank you in advance for your help and I'm terribly sorry if my questions title is too long and confusing. I'm certainly working on formatting better questions and building a stronger rep on SO.
https://repl.it/#CharChar5/Code-Challenge
Currently this is my code:
jjChallenge=(j)=>{
const len = j.length;
const newArray = [];
for(var i = 0; i<j.length; i++){
if (j[i] == 9) {
if(j[i-1] == 9) {
n = 0;
} else {
newArray[i-1] = newArray[i-1] + 1;
n = 0;
}
newArray.push(n);
} else {
newArray.push(j[i]);
}
}
console.log(newArray)
}
jjChallenge([2,9,9,9]) //works and returns [3,0,0,0]
//[2,9,8,9] doesnt work and returns [3,0,9,0]
Reverse it and increment with carry and then reverse it back
Something like
eg
function incrementIntArray(arr) {
var reverseArray = arr.reverse();
var newReverseArray = [];
var carry = false;
for (var i = 0; i < arr.length; i++) {
var curNum = reverseArray[i];
if (i == 0 || carry) curNum++;
if (curNum > 9) {
carry = true;
curNum = 0;
} else {
carry = false;
}
newReverseArray[i] = curNum;
}
return newReverseArray.reverse();
}
var arr1 = [1, 8, 9];
var arr2 = [1, 2, 3, 9, 1];
var arr3 = [5, 7, 9, 9];
console.log(incrementIntArray(arr1)); //outputs [1,9,0]
console.log(incrementIntArray(arr2)); //outputs [1,2,3,9,2]
console.log(incrementIntArray(arr3)); //outputs [5,8,0,0]
Your code was trying to carry, but it's difficult to carry when coming from the top down, hence the reverse and then its easier to carry from bottom up
Here ya go:
jjChallenge=(arr)=>{
newArray=arr.map((element) => {
return element==9?0:element+1
})
return newArray
}
jjChallenge([2,9,9,9])
Just sum the digits up and then plus one. After that, split it.
Simple and Clean that complies with
you can't join() or concat(). You cannot change the array in any way other than adding to it.
addOne = (data) => {
let sum = 0, digit = data.length - 1
data.forEach(n => sum += n * (10 ** digit--))
return (sum + 1).toString().split("")
}
console.log(addOne([1,8,9]))
console.log(addOne([1,2,3,9,1]))
console.log(addOne([5,7,9,9]))

Comparing arguments with an arguments in JavaScript

Please help me with this code; I am trying to compare arguments with an array elements and return when it matches, I don't know what is wrong with this code, it returns 1 rather than an array , thanks.
const removeFromArray = function() {
var delArgs = [] ;
//convert the arguments to an array called 'args'.
var args = Array.from(arguments);
var Arr = args[0];
//using foreach() and forloop to compare arguments with Arr elements.
Arr.forEach(function(x){
for (var j=1 ; j < args.length ; j++){
if(x == args[j]){
delArgs = delArgs.push(x);
}
}
});
return delArgs;
}
removeFromArray([1,2,3,4,5,6] , 5);
1
delArgs = delArgs.push(x);
You're overwriting delArgs with the return value from push, which is the new length of the array.
Don't do that.
since the question is already answered, you could use this for shorter code
const removeFromArray = (array, ...args) => {
return args.filter( arg => array.includes(arg) )
}
console.log(removeFromArray([1, 2, 3, 4, 5, 6], 5,6));

jQuery script not working with pre populated Array

I hope I am not repeating an existing question, I have tried really hard to find what I need on the site, but now feel I need to ask the question, so here goes, I hope you guys can help me out :s
I have an array;
var 1Results = somecontent;
var 2Results = somecontent;
var 3Results = somecontent;
var 4Results = somecontent;
var nomResults = 1Results + 2Results + 3Results + 4Results;
I have a script that is supposed to weed out the duplicate numbers and display them (in sorted_arr);
var arr = nomResults;
var sorted_arr = arr.sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
This script doesn't work, however is I change the script to this;
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sorted_arr = arr.sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
It works fine, any ideas why .sort() won't work with my pre popluated array?
Any help would be greatly appreciated.
You have to use brackets notation to add elements to your new Array like :
var arr = [Results1, Results2...];
Or Array.prototype.push() :
var arr = [];
arr.push(Results1);
arr.push(Results2);
//...
Plus you can use a specific function for sorting, either declaring a new function compare :
function compare(a, b) {
return a - b;
}
Which will use actual values of your array (and not Strings, as specified in your comments).
Then you pass it to sort :
arr = arr.sort(compare);
Or directly use anonymous function, if you don't need it more than one time :
arr = arr.sort(function(a, b) {
return a - b;
});
Two issues I can see in your code.
The variable names must not begin with a number
var nomResults is not an array but a string
The below code works for me just fine-
var results1 = "this",
results2="is",
results3="an",
results4="array",
theArray = [results1, results2, results3, results4];
console.log(theArray);
["this", "is", "an", "array"]
console.log(theArray.sort());
["an", "array", "is", "this"]
I was building my array wrong!!! Thanks guys, I knew it would be something simple :)
Instead of this;
var nomResults = 1Results + 2Results + 3Results + 4Results;
I needed to do this;
var nomResults = [Results1, Results2, Results3, Results4];
I've been looking at this for so long, I didn't see it. My script is all working now and great, errors are all gone, this is amazing. Many props and thanks to #jpreynat Thank you SO much :) I need a holiday....

Is there a more concise way to initialize empty multidimensional arrays?

I've been trying to find a reasonably concise way to set the dimensions of an empty multidimensional JavaScript array, but with no success so far.
First, I tried to initialize an empty 10x10x10 array using var theArray = new Array(10, 10 10), but instead, it only created a 1-dimensional array with 3 elements.
I've figured out how to initialize an empty 10x10x10 array using nested for-loops, but it's extremely tedious to write the array initializer this way. Initializing multidimensional arrays using nested for-loops can be quite tedious: is there a more concise way to set the dimensions of empty multidimensional arrays in JavaScript (with arbitrarily many dimensions)?
//Initializing an empty 10x10x10 array:
var theArray = new Array();
for(var a = 0; a < 10; a++){
theArray[a] = new Array();
for(var b = 0; b < 10; b++){
theArray[a][b] = new Array();
for(var c = 0; c < 10; c++){
theArray[a][b][c] = 10
}
}
}
console.log(JSON.stringify(theArray));
Adapted from this answer:
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[i] = createArray.apply(this, args);
}
return arr;
}
Simply call with an argument for the length of each dimension.
Usage examples:
var multiArray = createArray(10,10,10); Gives a 3-dimensional array of equal length.
var weirdArray = createArray(34,6,42,2); Gives a 4-dimensional array of unequal lengths.
function multiDimArrayInit(dimensions, leafValue) {
if (!dimensions.length) {
return leafValue;
}
var arr = [];
var subDimensions = dimensions.slice(1);
for (var i = 0; i < dimensions[0]; i++) {
arr.push(multiDimArrayInit(subDimensions, leafValue));
}
return arr;
}
console.log(multiDimArrayInit([2,8], "hi")); // counting the nested "hi"'s yields 16 of them
demo http://jsfiddle.net/WPrs3/
Here is my take on the problem: nArray utility function
function nArray() {
var arr = new Array();
var args = Array.prototype.slice.call(arguments, 1);
for(var i=0;i<arguments[0];i++) {
arr[i] = (arguments.length > 1 && nArray.apply(this, args)) || undefined;
}
return arr;
}
Usage example:
var arr = nArray(3, 3, 3);
Results in 3x3x3 array of undefined values.
Running code with some tests also available as a Fiddle here: http://jsfiddle.net/EqT3r/7/
The more dimension you have, the more you have interest in using one single flat array and a getter /setter function for your array.
Because for a [d1 X d2 X d3 X .. X dn] you'll be creating d2*d3*...*dn arrays instead of one, and when accessing, you'll make n indirection instead of 1.
The interface would look like :
var myNArray = new NArray(10,20,10);
var oneValue = myNArray.get(5,8,3);
myNArray.set(8,3,2, 'the value of (8,3,2)');
the implementation depends on your preference for a fixed-size
n-dimensionnal array or an array able to push/pop and the like.
A more succinct version of #chris code:
function multiDim (dims, leaf) {
dims = Array.isArray (dims) ? dims.slice () : [dims];
return Array.apply (null, Array (dims.shift ())).map (function (v, i) {
return dims.length
? multiDim (dims, typeof leaf == 'string' ? leaf.replace ('%i', i + ' %i') : leaf)
: typeof leaf == 'string' ? leaf.replace ('%i', i) : leaf;
});
}
console.log (JSON.stringify (multiDim ([2,2], "hi %i"), null, ' '));
Produces :
[
[
"hi 0 0",
"hi 0 1"
],
[
"hi 1 0",
"hi 1 1"
]
]
In this version you can pass the first argument as a number for single dimension array.
Including %i in the leaf value will provide index values in the leaf values.
Play with it at : http://jsfiddle.net/jstoolsmith/r3eMR/
Very simple function, generate an array with any number of dimensions. Specify length of each dimension and the content which for me is '' usually
function arrayGen(content,dims,dim1Len,dim2Len,dim3Len...) {
var args = arguments;
function loop(dim) {
var array = [];
for (var a = 0; a < args[dim + 1]; a++) {
if (dims > dim) {
array[a] = loop(dim + 1);
} else if (dims == dim) {
array[a] = content;
}
}
return array;
}
var thisArray = loop(1);
return thisArray;
};
I use this function very often, it saves a lot of time

Categories