build arrays to show index number - javascript

I have an array that looks like:
var myArray = [12, 24, 36, 48, 60, 15, 30];
I need to build a new array of arrays from this to show the index number from the original array in the new array. The final result should look like the following:
var myNewArray = [
[1, 12],
[2, 24],
[3, 36],
[4, 48],
[5, 60],
[6, 15],
[7, 30]
];

You can use
Array.prototype.map(), and then generate new array based on value and index of that array.
Demo
var myArray = [12, 24, 36, 48, 60, 15, 30],
newArray = myArray.map(function (value, index) {
return [index + 1, value];
});
FYI: - JavaScript arrays are zero-indexed: the first element of an array is at index 0

var myArray= [12, 24, 36, 48, 60, 15, 30],
myArrayIndexed= myArray.map(function(itm, i){
return [i+1, itm];
});
myArrayIndexed.join(']\n[');
/* returned value: */ [
[1, 12],
[2, 24],
[3, 36],
[4, 48],
[5, 60],
[6, 15],
[7, 30]
]

It's as simple as that:
var myArray = [12, 24, 36, 48, 60, 15, 30];
var myNewArray = [];
for (var i = 0; i < myArray.length; i++) {
myNewArray.push([i+1,myArray[i]]);//or just i depending on the index you need
}
Even a faster way is to cache the length of the array:
for (var i = 0, var l = myArray.length; i < l; i++) {}
To my knowledge and research so far - Javascript's native for loop is quicker than array map for iterating through the array. Here is an interesting benchmark.
Hope this helps!

Related

How to make nested array into a single array in javascript

I got stuck in some problem and unable to get any idea of how to resolve it.As I have a nested
array given below:
arr = [1,2,3,4,5,6,[7,8,9,[10,[21,22,[24,25,26],23],11],12,13],14,15,16,[17,18],19,20]
On using flat() method below method:
arr.flat()
it gives below output:
[1,2,3,4,5,6,7,8,9,[ 10, [ 21, 22, [Array], 23 ],11 ],12,13,14,15,16,17,18,19,20]
How can I convert this nested array into a single array.Someone let me know.
You can use the flat method here.
arr.flat(Infinity);
const arr = [
1,
2,
3,
4,
5,
6, [7, 8, 9, [10, [21, 22, [24, 25, 26], 23], 11], 12, 13],
14,
15,
16, [17, 18],
19,
20,
];
const result = arr.flat(Infinity);
console.log(result);

Complete missing sequence in array with zeros in javascript

I have the following array:
const arr = [
[5, 0.2],
[7, 0.6],
[8, 0.3],
[10, 0.4]
];
console.log(arr)
I need to ensure that the first element of the array is a sequence from 5 to 10:
[5, 6, 7, 8, 9, 10]
In the above example, these numbers within the sequence are missing:
[6, 9]
If they are missing, I need to include them with zeros:
const expectedResult = [
[5, 0.2],
[6, 0],
[7, 0.6],
[8, 0.3],
[9, 0],
[10, 0.4]
];
console.log(expectedResult)
Any ideas on how to achieve this?
You could map the missing parts with a closure over the actual index of the given array.
const
array = [[5, 0.2], [7, 0.6], [8, 0.3], [10, 0.4]],
result = Array.from(
{ length: 6 },
(i => (_, j) => array[i]?.[0] === j + 5 ? array[i++] : [j + 5, 0])(0)
);
console.log(result);

Finding all even factorizations of a given number n - javascript python

Currently i am implementing an algorithm that relies on finding all even factorizations of a given number n, including n.
I've tried some things, but overall i am not able to handle the problem well. Maybe its a good idea to handle it recursively, but i am not that good with javascript yet, especially with the higher level aspects of the language which might come in handy.
function evens(n) {
evens = []
for (var i = 2; i < n/2 - 1; i++){
if (i % 2 != 0){
continue;
}
else {
if ((n/i) % 2 == 0) {
evens.push([n/i, i])
}
}
}
return evens
}
This is some code that goes some of the way, but i am not yet able to recursively implement it considering all the right base cases.
I also thought that it could be done with a tree like structure in which paths are even factors, but my cs knowledge is pretty bad.
Suggestions in Python are also welcome, but javascript would be best.
Just to make everything more clear: all even factorizations of 136 for example are [[68, 2], [34, 2, 2], [34, 4], [136]].
Thankfull for any help :)
Maybe its a good idea to handle it recursively
Here's my attempt at a recursive solution in Python:
def even_factorization(n):
solutions = []
def even_divisors(n): # 136 generates [2, 4, 8, 34, 68, 136]
return (d for d in range(2, n + 1, 2) if n % d == 0)
def remove_similarities(array): # [[2, 2, 34], [2, 34, 2], [34, 2, 2]] -> [[2, 2, 34]]
return list(map(list, set(map(lambda a: tuple(sorted(a)), array))))
for divisor in even_divisors(n):
if divisor == n:
solutions.append([divisor])
else:
for solution in even_factorization(n // divisor):
solutions.append([divisor] + solution)
return remove_similarities(solutions) # return 'solutions' to see raw data
For 136 returns:
[[2, 2, 34], [4, 34], [2, 68], [136]]
for 218960 returns:
[[184, 1190], [8, 27370], [4, 54740], [2, 70, 1564], [56, 3910], [2, 2, 170, 322],
[280, 782], [70, 3128], [4, 46, 1190], [2, 2, 34, 1610], [2, 14, 34, 230],
[2, 14, 7820], [20, 34, 322], [10, 14, 34, 46], [14, 92, 170], [20, 46, 238],
[218960], [2, 322, 340], [10, 68, 322], [34, 46, 140], [10, 14, 1564],
[2, 10, 10948], [10, 92, 238], [4, 170, 322], [92, 2380], [14, 20, 782],
[10, 21896], [238, 920], [28, 34, 230], [10, 28, 782], [2, 2, 46, 1190],
[2, 28, 3910], [10, 34, 644], [34, 6440], [2, 92, 1190], [46, 4760], [2, 170, 644],
[2, 68, 1610], [4, 70, 782], [340, 644], [2, 34, 46, 70], [2, 20, 5474],
[14, 68, 230], [2, 34, 3220], [4, 34, 1610], [4, 10, 5474], [28, 7820],
[14, 34, 460], [322, 680], [10, 46, 476], [2, 2, 54740], [4, 230, 238],
[2, 2, 2, 27370], [34, 70, 92], [2, 140, 782], [14, 15640], [2, 10, 46, 238],
[2, 10, 14, 782], [2, 14, 46, 170], [2, 238, 460], [136, 1610], [2, 2, 10, 5474],
[20, 10948], [4, 14, 3910], [40, 5474], [2, 2, 70, 782], [2, 2, 230, 238],
[230, 952], [68, 3220], [2, 46, 2380], [2, 230, 476], [2, 10, 34, 322],
[140, 1564], [460, 476], [170, 1288], [2, 4, 27370], [46, 68, 70], [14, 46, 340],
[2, 109480], [28, 46, 170], [2, 2, 14, 3910]]
After cdlane correctly pointed out a flaw in my solution, I have retracted my original solution, and ported cdlane's elegant python solution to javascript.
function even_factorization(n) {
let solutions = [];
function even_divisors(n) {
var divisors = [];
for (let i = 2; i <= n; i += 2) {
if (n % i === 0) divisors.push(i);
}
return divisors;
}
function remove_similarities(combos) {
for (let i = 0; i < combos.length; i++) {
for (let j = i + 1; j < combos.length; j++) {
if (combos[i].sort((a,b) => a - b).join(" ") === combos[j].sort((a,b) => a - b).join(" ")) {
combos.splice(j--,1);
}
}
}
return combos;
}
even_divisors(n).forEach(divisor => {
if (divisor === n)
solutions.push([divisor]);
else {
even_factorization(n / divisor).forEach(solution => {
solutions.push([divisor, ...solution]);
});
}
});
return remove_similarities(solutions);
}
Running with 218960 returns...
[[2,2,2,27370],[2,2,10,5474],[2,2,14,3910],[2,2,34,1610],[2,2,46,1190],[2,2,70,782],[2,2,170,322],[2,2,230,238],[2,2,54740],[2,4,27370],[2,10,14,782],[2,10,34,322],[2,10,46,238],[2,10,10948],[2,14,34,230],[2,14,46,170],[2,14,7820],[2,20,5474],[2,28,3910],[2,34,46,70],[2,34,3220],[2,46,2380],[2,68,1610],[2,70,1564],[2,92,1190],[2,140,782],[2,170,644],[2,230,476],[2,238,460],[2,322,340],[2,109480],[4,10,5474],[4,14,3910],[4,34,1610],[4,46,1190],[4,70,782],[4,170,322],[4,230,238],[4,54740],[8,27370],[10,14,34,46],[10,14,1564],[10,28,782],[10,34,644],[10,46,476],[10,68,322],[10,92,238],[10,21896],[14,20,782],[14,34,460],[14,46,340],[14,68,230],[14,92,170],[14,15640],[20,34,322],[20,46,238],[20,10948],[28,34,230],[28,46,170],[28,7820],[34,46,140],[34,70,92],[34,6440],[40,5474],[46,68,70],[46,4760],[56,3910],[68,3220],[70,3128],[92,2380],[136,1610],[140,1564],[170,1288],[184,1190],[230,952],[238,920],[280,782],[322,680],[340,644],[460,476],[218960]]
...and running with 136 returns...
[[2,2,34],[2,68],[4,34],[136]]

Get the intersection of three arrays in JavaScript

I need to make a utility that checks the intersection of 3 arrays.
Here's my implementation in JS:
function intersection(array1, array2, array3) {
let intermediateList = [];
let intermediateList2 = [];
for (let i = 0; i < array1.length; i++) {
if (!(array2.indexOf(array1[i]) == -1)) {
intermediateList.push(array1[i]);
}
for (let j = 0; j < intermediateList.length; j++) {
if (!(intermediateList.indexOf(array3[j]) == -1)) {
intermediateList2.push(intermediateList[i]);
}
}
}
let endList = [ ...intermediateList, ...intermediateList2];
return endList;
}
intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20])
//  [5, 15] /--> fine
intersection([5, 10, 15, 20, 40, 32], [32, 15, 88, 1, 5, 7, 40], [1, 10, 15, 5, 20, 40, 32])
// [5, 15, 40, 32, undefined, undefined, undefined] /--> can someone spot why do I get those undefined values?
How would you implement this with reduce?
Your function has a nested for loop which iterates the intermediateList every time where the outer loop is running. Then you push a value with index i instead of index j, but this should work only if the two for loops are not nested but chained.
function intersection(array1, array2, array3) {
let intermediateList = [];
let intermediateList2 = [];
for (let i = 0; i < array1.length; i++) {
if (array2.indexOf(array1[i]) !== -1) {
intermediateList.push(array1[i]);
}
}
for (let j = 0; j < intermediateList.length; j++) {
if (array3.indexOf(intermediateList[j]) !== -1) {
intermediateList2.push(intermediateList[j]);
}
}
return intermediateList2;
}
console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));
console.log(intersection([5, 10, 15, 20, 40, 32], [32, 15, 88, 1, 5, 7, 40], [1, 10, 15, 5, 20, 40, 32]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could reduce the arguments and return a single array with common values.
const intersection = (...array) => array.reduce((a, b) => a.filter(v => b.includes(v)));
console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));
console.log(intersection([5, 10, 15, 20, 40, 32], [32, 15, 88, 1, 5, 7, 40], [1, 10, 15, 5, 20, 40, 32]));

jquery multidimensional array shuffle random

I want to minimize my code from:
myArrayA = [1, 2, 3, 4, 5];
fisherYates(myArrayA);
myArrayB = [6, 7, 8, 9, 10];
fisherYates(myArrayB);
myArrayC = [11, 12, 13, 14, 15];
fisherYates(myArrayC);
myArrayD = [16, 17, 18, 19, 20];
fisherYates(myArrayD);
myArrayE = [21, 22, 23, 24, 25];
fisherYates(myArrayE);
To:
var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
fisherYates(multArr);
The output I want is like this:
[4,2,3,5,1],[7,10,6,9,8],[11,15,12,14,13],[18,17,16,20,19],[22,21,25,23,24]
I tried this code:
http://jsfiddle.net/arrow/yFn8U/
function fisherYates(myArray) {
var i = myArray.length, j, tempi, tempj;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = myArray[i];
tempj = myArray[j];
myArray[i] = tempj;
myArray[j] = tempi;
}
}
var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
fisherYates(multArr);
But my code only randomizes the order of the chunks not the values in each chunk.
The output I want is like this:
[4,2,3,5,1],[7,10,6,9,8],[11,15,12,14,13],[18,17,16,20,19],[22,21,25,23,24]
I want each chunk inside the array to be in the same order but each chunk must be randomized.
Is there a way to do this with jQuery?
I also wonder how to get values from the shuffled/randomized array?
At the moment I get the values like this:
myArrayA[i]
myArrayB[i]
myArrayC[i]
myArrayD[i]
myArrayE[i]
I would guess I will get them with something like:
multArr [[0][i]];
multArr [[1][i]];
multArr [[2][i]];
multArr [[3][i]];
multArr [[4][i]];
Finally I wonder if minimizing the code will give better performance?
If you simply want to run an operation over all the elements in an array, then you should use map or forEach. I'm sure jquery provides shims for these methods in older browsers. So if we assume you're using your original fisherYates function unaltered, we might have something like this:
var multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
multArr.forEach(fisherYates);
On accessing the elements, you're almost right, but you have one set too many of brackets :
multArr[1]; // == [6, 7, 8, 9, 10]
multArr[1][3]; // == 9
I wouldn't speculate about the performance, if you're really worried you should put together a jsperf test case.
All you need is jQuery's .each() method, like so:
$.each(multArr, function(i) { fisherYates(this) });
See console on this working example
Fiddle Code
function fisherYates(myArray) {
var i = myArray.length, j, tempi, tempj;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = myArray[i];
tempj = myArray[j];
myArray[i] = tempj;
myArray[j] = tempi;
}
}
$(function() {
$("button").on("click", function(e) {
multArr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]];
$.each(multArr, function(i) { fisherYates(this) });
console.log(multArr)
})
})
Check out my code here. Basically just looped over the elements of the multidimensional array and run the fisherYates on them like so:
function fisherYates(myArray) {
for(var i = 0; i< myArray.length; i++) {
k = myArray[i].length;
while(k--){
j = Math.floor(Math.random() * (myArray.length - 1));
tempk = myArray[i][k];
tempj = myArray[i][j];
myArray[i][k] = tempj;
myArray[i][j] = tempk;
}
}
}
Now if you wanted to do this for an n-dimensional array you're going to have to do it recursively, which would be fun, but I think that is more than you were asking for. If not I can update it later.

Categories