multiple arrays into one array - javascript

I need help with the five.myArraysCombined property.
I need it to equal just 1 array (which it currently does in fiddle) and I need it to NOT add any numbers together. (so each number in the array shouldn't be over 20, just like no number in the other arrays are over 20)
http://jsfiddle.net/Dc6HN/1/
For example, if the five arrays are like this
five.myArray1 = [7,2,9,19,3];
five.myArray2 = [6,18,8,1,7];
five.myArray3 = [7,19,4,8,2];
five.myArray4 = [11,9,1,14,5];
five.myArray5 = [3,18,8,9,2];
then the all those arrays combined should be like this
five.myArraysCombined = [7,2,9,19,3,6,18,8,1,7,7,19,4,8,2,11,9,1,14,5,3,18,8,9,2];
Relevant code :
function theNumberClass() {
this.myArray = [[],[],[],[],[]];
this.myArraysCombined = [];
}
var five = new theNumberClass();
function prePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
var zzz = [];
for (var x = 0; x < theNum; x += 1) {
pickNumbers(objName.myArray[x], theNum, theSumNum, theMaxNum, theMinNum);
zzz += objName.myArray[x];
}
objName.myArraysCombined.push(zzz);
}
prePickNumbers(five, 5, 40, 20, 1);
My latest attempt was with var zzz and then pushing it to the property, but when I do that it adds up the numbers in the array at times, which is not what I need.
I've also tried several attempts using the .concat(), but it seems to turn it into a string and sometimes also adds up the numbers.

Suppose you have those arrays :
var a = [1, 2, 3]
var b = [4, 5, 6]
var c = [8]
Then you can get a merge of all those with
var all = [].concat.apply([],[a,b,c])
or with
var all = [a,b,c].reduce(function(merged, arr){ return merged.concat(arr) })
In both cases you get
[1, 2, 3, 4, 5, 6, 8]
The first solution is simpler, the second one is more extensible if you want, for example, to remove duplicate or do any kind of filtering/transformation.

I would guess that the issue is the "+=" operator. This operator is used to sum values, not add new elements to an array. Take the following line of code as an example:
zzz += objName.myArray[x];
What I am guessing is that "myArray[x]" is getting added to the value of zzz instead of getting appended to the end of the array. When adding elements to an array in javascript, push is the best option. A better way to write this line is:
zzz.push(objName.myArray[x]);
The question was a bit confusing so I'm not sure if this is what you are looking for but hopefully it will help anyways.

five.reduce(function(o,n){return o.concat(n)},[])
This will reduce the array to a single value, in this case an array of numbers. You can look up Array.reduce() on MDN for more info.

After many hours trying all suggestions left on this thread and another one, and trying multiple other things. I think I finally found a very simple way to do this. And it's the only way I tried that works 100% like I want.
http://jsfiddle.net/Dc6HN/2/
function prePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
for (var x = 0; x < theNum; x += 1) {
pickNumbers(objName.myArray[x], theNum, theSumNum, theMaxNum, theMinNum);
objName.myArraysCombined.push(objName.myArray[x]);
}
objName.myArraysCombined = objName.myArraysCombined.toString();
objName.myArraysCombined = objName.myArraysCombined.split(',');
}

Related

Spinning the elements of an array clockwise in JS

I am supposed to rotate an array of integers clockwise in JS.
Here is my code for it:
function rotateArray(N, NArray)
{
//write your Logic here:
for(j=0;j<2;j++){
var temp=NArray[N-1];
for(i=0;i<N-1;i++){
NArray[i+1]=NArray[i];
}
NArray[0]=temp;
}
return NArray;
}
// INPUT [uncomment & modify if required]
var N = gets();
var NArray = new Array(N);
var temp = gets();
NArray = temp.split(' ').map(function(item) { return parseInt(item, 10);});
// OUTPUT [uncomment & modify if required]
console.log(rotateArray(N, NArray));
The code accepts an integer N which is the length of the array. The input is as follows:
4
1 2 3 4
The correct answer for this case is supposed to be
4 1 2 3
But my code returns
4 1 1 1
I cannot find where my code is going wrong. Please help me out.
All you need to do is move one item from the end of the array to the beginning. This is very simple to accomplish with .pop() (removes an item from the end of an array), then declare a new array with that element as the first:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem, ...NArray];
}
console.log(rotateArray(1, [1, 2, 3, 4]));
Doing anything else, like using nested loops, will make things more unnecessarily complicated (and buggy) than they need to be.
If you don't want to use spread syntax, you can use concat instead, to join the lastItem with the NArray:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem].concat(NArray);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
If you aren't allowed to use .pop, then look up the last element of the array by accessing the array's [length - 1] property, and take all elements before the last element with .slice (which creates a sub portion of the array from two indicies - here, from indicies 0 to the next-to-last element):
function rotateArray(N, NArray) {
const lastItem = NArray[NArray.length - 1];
const firstItems = NArray.slice(0, NArray.length - 1);
return [lastItem].concat(firstItems);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
function rotate(array,n){
Math.abs(n)>array.length?n=n%array.length:n;
if(n<0){
n=Math.abs(n)
return array.slice(n,array.length).concat(array.slice(0,n));
}else{
return array.slice(n-1,array.length).concat(array.slice(0,n-1));
}
}
console.log(rotate([1, 2, 3, 4, 5],-3));
The answer by #CertainPerformance is great but there's a simpler way to achieve this. Just combine pop with unshift.
let a = [1,2,3,4];
a?.length && a.unshift(a.pop());
console.log(a);
You need to check the length first so you don't end up with [undefined] if you start with an empty array.

Javascript create an array with unique combination of values [duplicate]

This question already has answers here:
Find ith permutation in javascript
(3 answers)
Closed 4 years ago.
Despite reading a lot of Q/A about permutation/combination: Finding All Combinations of JavaScript array values + JavaScript - Generating combinations from n arrays with m elements I have not found the right way to get the kind of result I'm looking for.
I got a 10 values array:
var arr = [0,1,2,3,4,5,6,7,8,9];
If I'm right, the number of all possible permuted arrays of unique values (no duplicates):
[5,9,1,8,2,6,7,0,4,3] [4,8,0,2,1,9,7,3,6,5] ...
is 2x3x4x5x6x7x8x9x10 = 3628800
I'm trying to produce a function to dynamically create the 'n' array. For example:
function createArray(0) -> [0,1,2,3,4,5,6,7,8,9]
function createArray(45648) -> [0,1,5,3,2,8,7,9,6] (something like...)
function createArray(3628800) -> [9,8,7,6,5,4,3,2,1,0]
The way I'm figuring to achieve it is:
createArray(1) permutes the 2 last signs (8,9 -> 9,8)
createArray(2->6) permutes the 3 last signs (8,7,9 -> 9,8,7)
createArray(3628800) : all values are permuted (9->0)
Do you think it's possible/easy to do, and if yes how to proceed ?
[EDIT]
Thanks for helpfull answers
function permute(permutation, val) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p,
n = 0;
while (i < length) {
if (c[i] < i) {
if (n <= val) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
if (n == val) {
arr = permutation.slice();
console.log("n="+n+"\n"+arr);
console.log( 'Duration: '+((new Date() - t1)/1000)+'s' );
break;
}
else { n+=1; }
}
} else {
c[i] = 0;
++i;
}
}
}
let t1 = new Date();
permute([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 100000); // <- array requested
console : n=100000 + 0,5,8,1,7,2,3,6,4,9 + Duration: 0.004s
As this question doesn't decribe a specific programming problem but rather a task, and at that a rather complex one, you shoulnd't expect a full solution as an answer, but i'll try describing a possible method of doing this:
As you said, the number of permutations is 2x3x4x...
You could check if n > 2, if true, then check if n > 2x3, if true check if n > 2x3x4. That way you would know how many of the tailing array indexes you want to permutate. Then you would have to make sure to calculate the permutations in a sorted linear way that doesn't generate the same permutation twice. Thats a math problem, the coding itself should be rather easy (something along the lines of switch the position n times at changing indexes).
Not sure if this is the answer you're looking for, but making a unique permutation algorithm sounds rather complex (see for example this answer to another question https://stackoverflow.com/a/11425168/9521900) which links to this wikipedia article https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order on generating in lexicographic order.
EDIT: From Raj Sharmas comment on your question, this answer on generating permutations seems valuable too:
https://stackoverflow.com/a/37580979/3090583

Duplicate an array an arbitrary number of times (javascript)

Let's say I'm given an array. The length of this array is 3, and has 3 elements:
var array = ['1','2','3'];
Eventually I will need to check if this array is equal to an array with the same elements, but just twice now. My new array is:
var newArray = ['1','2','3','1','2','3'];
I know I can use array.splice() to duplicate an array, but how can I duplicate it an unknown amount of times? Basically what I want is something that would have the effect of
var dupeArray = array*2;
const duplicateArr = (arr, times) =>
Array(times)
.fill([...arr])
.reduce((a, b) => a.concat(b));
This should work. It creates a new array with a size of how many times you want to duplicate it. It fills it with copies of the array. Then it uses reduce to join all the arrays into a single array.
The simplest solution is often the best one:
function replicate(arr, times) {
var al = arr.length,
rl = al*times,
res = new Array(rl);
for (var i=0; i<rl; i++)
res[i] = arr[i % al];
return res;
}
(or use nested loops such as #UsamaNorman).
However, if you want to be clever, you also can repeatedly concat the array to itself:
function replicate(arr, times) {
for (var parts = []; times > 0; times >>= 1) {
if (times & 1)
parts.push(arr);
arr = arr.concat(arr);
}
return Array.prototype.concat.apply([], parts);
}
Basic but worked for me.
var num = 2;
while(num>0){
array = array.concat(array);
num--}
Here's a fairly concise, non-recursive way of replicating an array an arbitrary number of times:
function replicateArray(array, n) {
// Create an array of size "n" with undefined values
var arrays = Array.apply(null, new Array(n));
// Replace each "undefined" with our array, resulting in an array of n copies of our array
arrays = arrays.map(function() { return array });
// Flatten our array of arrays
return [].concat.apply([], arrays);
}
console.log(replicateArray([1,2,3],4)); // output: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
What's going on?
The first two lines use apply and map to create an array of "n" copies of your array.
The last line uses apply to flatten our recently generated array of arrays.
Seriously though, what's going on?
If you haven't used apply or map, the code might be confusing.
The first piece of magic sauce here is the use of apply() which makes it possible to either pass an array to a function as though it were a parameter list.
Apply uses three pieces of information: x.apply(y,z)
x is the function being called
y is the object that the function is being called on (if null, it uses global)
z is the parameter list
Put in terms of code, it translates to: y.x(z[0], z[1], z[2],...)
For example
var arrays = Array.apply(null, new Array(n));
is the same as writing
var arrays = Array(undefined,undefined,undefined,... /*Repeat N Times*/);
The second piece of magic is the use of map() which calls a function for each element of an array and creates a list of return values.
This uses two pieces of information: x.map(y)
x is an array
y is a function to be invoked on each element of the array
For example
var returnArray = [1,2,3].map(function(x) {return x + 1;});
would create the array [2,3,4]
In our case we passed in a function which always returns a static value (the array we want to duplicate) which means the result of this map is a list of n copies of our array.
You can do:
var array = ['1','2','3'];
function nplicate(times, array){
//Times = 2, then concat 1 time to duplicate. Times = 3, then concat 2 times for duplicate. Etc.
times = times -1;
var result = array;
while(times > 0){
result = result.concat(array);
times--;
}
return result;
}
console.log(nplicate(2,array));
You concat the same array n times.
Use concat function and some logic: http://www.w3schools.com/jsref/jsref_concat_array.asp
Keep it short and sweet
function repeat(a, n, r) {
return !n ? r : repeat(a, --n, (r||[]).concat(a));
}
console.log(repeat([1,2,3], 4)); // [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
http://jsfiddle.net/fLo3uubk/
if you are inside a loop you can verify the current loop index with the array length and then multiply it's content.
let arr = [1, 2, 3];
if(currentIndex > arr.length){
//if your using a loop, make sure to keep arr at a level that it won't reset each loop
arr.push(...arr);
}
Full Example:
https://jsfiddle.net/5k28yq0L/
I think you will have to write your own function, try this:
function dupArray(var n,var arr){
var newArr=[];
for(var j=0;j<n;j++)
for(var i=0;i<arr.length;i++){
newArr.push(arr[i]);
}
return newArr;
}
A rather crude solution for checking that it duplicates...
You could check for a variation of the length using modulus:
Then if it might be, loop over the contents and compare each value until done. If at any point it doesn't match before ending, then it either didn't repeat or stopped repeating before the end.
if (array2.length % array1.length == 0){
// It might be a dupe
for (var i in array2){
if (i != array1[array2.length % indexOf(i)]) { // Not Repeating }
}
}

What is the way of declaring an array in JavaScript?

I'm just learning JavaScript and it seems like there are a number of ways to declare arrays.
var myArray = new Array()
var myArray = new Array(3)
var myArray = ["apples", "bananas", "oranges"]
var myArray = [3]
What are their difference, and what are the preferred ways?
According to this website the following two lines are very different:
var badArray = new Array(10); // creates an empty Array that's sized for 10 elements
var goodArray= [10]; // creates an Array with 10 as the first element
As you can see these two lines do two very different things. If you
had wanted to add more than one item then badArray would be
initialized correctly since Javascript would then be smart enough to
know that you were initializing the array instead of stating how many
elements you wanted to add.
Is what the authors trying to say is Array(10) creates an array with precisely 10 elements and [10] creates an array of undefined size with the 0th element being 10? Or what does this mean?
In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.
Be careful when using new Array().
var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]
The preferred way is using the [] syntax.
var x = []; // array of size 0
var y = [10] // array of size 1: [1]
var z = []; // array of size 0
z[2] = 12; // z is now size 3: [undefined, undefined, 12]
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:
function Array() { return []; }
alert(Array(1, 2, 3)); // An empty alert box
However, the larger issue is that of consistency. Someone refactoring code could come across this function:
function fetchValue(n) {
var arr = new Array(1, 2, 3);
return arr[n];
}
As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:
var arr = new Array(1);
To declare it:
var myArr = ["apples", "oranges", "bananas"];
To use it:
document.write("In my shopping basket I have " + myArr[0] + ", " + myArr[1] + ", and " + myArr[2]);
There are a number of ways to create arrays.
The traditional way of declaring and initializing an array looks like this:
var a = new Array(5); // declare an array "a", of size 5
a = [0, 0, 0, 0, 0]; // initialize each of the array's elements to 0
Or...
// declare and initialize an array in a single statement
var a = new Array(0, 0, 0, 0, 0);
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length); is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
You can declare like this
const [alice, bob] = [1, 2]
console.log(alice) // 1
console.log(bob) // 2

Javascript: is there a data structure, "matrix", thing[x][y]?

I don't know the terminology but I want to get it simpler:
var thingTopic1 =['hello','hallo', ..., 'hej'];
var thingTopic2 =['a','b',...,'c'];
...
var thingTopic999 =['x,'y',...,'?'];
so I want to access the data like thing[para1][para2], is there some ready data structure for it or do I need to create messy function with the things? Please, note that sizes of things differ.
You can have arrays of arrays, and the size of each row can be different.
var matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
];
The variable "matrix" will refer to an array with length 4. The syntax you use to refer to (say) the "5" in the second row is exactly what you suggested:
var theFive = matrix[1][1];
You can "build" a matrix like that incrementally of course.
var matrix = [];
for (var i = 1; i < 10; ++i) {
var row = ~~((i - 1) / 3);
if (!matrix[row]) matrix[row] = [];
matrix[row][(i - 1) % 3] = i;
}
matrix.push([0]);
When you set an integer-indexed "property" of an Array instance, Javascript makes sure that the "length" property of the array is updated. It does not allocate space for "holes" in the array, so if you set element number 200 first, there's still just one thing in the array, even though "length" would be 201.
No, there is no data structure for that, but you can easily accomplish it by combining arrays.
You can create an array that contains arrays, which is called a jagged array:
var thing = [
['hello','hallo','goddag','guten tag','nuqneH','hej'],
['a','b','c','d','e','f','g','h','i','j'],
['x,'y','z']
];
Notice how the inner arrays can have different length, which is where the term "jagged" comes from.
You can take advantages from OOP of ES6 :
class Matrix extends Array {
constructor(...rows) {
if(rows.some( r => !Array.isArray(r)))
throw new TypeError('Constructor accepts only rows as array')
super(...rows)
}
push(...rows) {
if(rows.some( r => !Array.isArray(r)))
throw new TypeError('Push method accepts array(s)')
super.push(...rows)
}
}
Use case 1:
Use case 2 :

Categories

Resources