How do I split an array into two-dimensional arrays? (JavaScript) [duplicate] - javascript

This question already has answers here:
Split array into chunks
(73 answers)
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I would like to create a two-dimensional array based on targetItems with the number of numbers in splitNumber and output it as follows.
const targetItems = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const splitNumber = 2;
We are looking for the following results.
[[1, 2, 3, 4, 5], [6, 7, 8, 9]];
Is there a good way?
I was thinking of using Math.round, etc. to carry it out if it can't be done evenly.
If the number of targetItems is 5 and the splitNumber is 2
[[1,2,3], [4,5]]
If the number of targetItems is 17 and the splitNumber is 2
[[1,2,3,4,5,6,7,8,9], [10,11,12,13,14,15,16,17]]
If the number of targetItems is 5 and the splitNumber is 3
[[1,2], [3,4], [5]]

Basically, we use the arary.slice(start,end) method splitNumber of times, having the bigger parts first. The results depend indeed on how you define the problem in the first place. So this code might need changes.
const targetItems = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function split(targetItems, splitNumber) {
const half = Math.ceil(targetItems.length / splitNumber);
var parts = [];
for (var i = 0; i < splitNumber; i++) {
parts.push(targetItems.slice(i * half, i * half + half))
}
return parts;
}
for (var i = 1; i <= targetItems.length; i++) {
console.log("split to " + i + " parts", JSON.stringify(split(targetItems, i)))
}
.as-console-wrapper {
max-height: 100% !important;
}

I used this code in my previous project:
var arr = [1,2,3,4,5,6,7,8,9,0]
const arr1l = Math.floor(arr.length/2)
const arr2l = arr.length-arr1l
const arr1 = arr.slice(0,arr1l)
const arr2 = arr.slice(arr1l,arr.length)
var new_arr=[arr1,arr2]
document.querySelector(".h1").innerHTML=arr1
document.querySelector(".h2").innerHTML=arr2
<p class="h1"></p>
<p class="h2"></p>

I used in this way.
const arr = [1,2,3,4,5,6,7,8,9,1,1,2];
function turnIntoTwoDimension(arr) {
let twoDimension = []
twoDimension.push(arr.slice(0,arr.length/2))
twoDimension.push(arr.slice(arr.length/2))
return twoDimension
}
console.log(turnIntoTwoDimension(arr));

const targetItems = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function split(targetItems, splitNumber) {
const half = Math.ceil(targetItems.length / splitNumber);
var parts = [];
for (var i = 0; i < splitNumber; i++) {
parts.push(targetItems.slice(i * half, i * half + half))
}
return parts;
}
for (var i = 1; i <= targetItems.length; i++) {
console.log("split to " + i + " parts", JSON.stringify(split(targetItems, i)))
}
.as-console-wrapper {
max-height: 100% !important;
}

Related

How to return an array of indexes from the first array which is the intersection of indexes from two sorted arrays?

I wrote a solution that allows me to get an array of indexes from the first array which is the intersection of indexes from two sorted arrays and I'd like to know why this solution is wrong. When I check it I get the correct array of indexes from the first array but the interviewer told me that this is wrong.
Thanks a lot for the help and explanations. I have no commercial experience yet. Sorry for some mistakes in English, as I am from Ukraine and I improve this language.
// first example of input:
// const arr1 = [1, 2, 2, 2];
// const arr2 = [1, 1, 2, 2];
// second example of input:
const arr1 = [1, 2, 2, 3, 4, 5, 6, 7, 9, 9, 20];
const arr2 = [1, 2, 3, 3, 5, 8, 9, 9, 21];
// first example of output:
// - [0, 1, 2]
// - [0, 1, 3]
// - [0, 2, 3]
// second example of output:
// - [0, 1, 3, 5, 8, 9]
// - [0, 2, 3, 5, 8, 9]
//function compareItemsFn, length1, length2 - from conditions to this task
const compareItemsFn = (index1, index2) => {
switch (true) {
case arr1[index1] === arr2[index2]: return 0;
case arr1[index1] < arr2[index2]: return -1;
case arr1[index1] > arr2[index2]: return 1;
default: return undefined;
}
};
const length1 = arr1.length;
const length2 = arr2.length;
// function intersectionIndexes - my solution
function intersectionIndexes(compareItemsFn, length1, length2) {
let indexesIntersectionArray = [];
let i = 0;
let j = 0;
while (i < length1 && j < length2) {
if (compareItemsFn (i, j) === 0) {
indexesIntersectionArray.push(i);
i++;
j++;
} else if (compareItemsFn (i, j) === 1) {
j++;
} else {
i++;
}
}
return indexesIntersectionArray;
};
const result = intersectionIndexes(compareItemsFn, length1, length2);
If you are certain that your solution works then perhaps it was not wrong in the sense that it gave the wrong answer but rather in the way you solved the problem.
The following code is a simplification of your solution. It takes the two arrays as parameters instead of the value of their length property so the solution isn't tied to the global variables arr1 and arr2. You should always favor implementing solutions that are generalised.
In place of your compareItemsFn function, the Math.sign() method from the standard library is used. Some times in interview situations you can be asked to implement functionality which can be found in the standard library and what the interviewer is looking to see is if you are aware of it.
function simplified(arrayOne, arrayTwo) {
let result = [];
let indexOne = 0;
let indexTwo = 0;
while (indexOne < arrayOne.length && indexTwo < arrayTwo.length) {
let signCheck = Math.sign(arrayOne[indexOne] - arrayTwo[indexTwo]);
if (signCheck == 0) {
result.push(indexOne);
indexOne++;
indexTwo++;
}
else if ( signCheck > 0) {
indexTwo++;
}
else {
indexOne++;
}
}
return result;
}

How to compare two array and store the similar element into another array in Javascript? [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Simplest code for array intersection in javascript
(40 answers)
Closed 1 year ago.
I wanted to compare two array and store the element that is present in both array into a new array. So I write this code but it didn't work.
var sampleArray = [1, 2, 3, 4, 5, 6, 7];
var sampleArray2 = [5, 6, 7, 8, 9, 10 ,11];
var similarElements =[];
for (let i = 0; i < sampleArray.length; i++) {
for (let j = 0; j < sampleArray2.length; j++) {
if (sampleArray[i] === sampleArray2[j]) {
similarElements.push();
}
}
}
console.log(similarElements);
let arr1 = [1, 2, 3, 4, 5, 6, 7];
arr2 = [5, 6, 7, 8, 9, 10 ,11];
hash = arr1.reduce((h,e)=> (h[e]=1, h), {}), //iterate first array once
common = arr2.filter(v=>hash[v]); //iterate secod array once
console.log('Cpmmon elements: ', common);
It searches for itself in sampleArray2, if it finds itself it'll add the number to similarArray
var sampleArray = [1, 2, 3, 4, 5, 6, 7];
var similarArray = [];
for (const num of sampleArray) {
if (sampleArray2.indexOf(num) {
similarArray.push(num);
}
}
var sampleArray = [1, 2, 3, 4, 5, 6, 7];
var sampleArray2 = [5, 6, 7, 8, 9, 10 ,11];
var similarElements =[];
for (let i = 0; i < sampleArray.length; i++) {
for (let j = 0; j < sampleArray2.length; j++) {
if (sampleArray[i] === sampleArray2[j]) {
similarElements.push(sampleArray[i]);
}
}
}
console.log(similarElements);

How to add an array of elements in order?

I have an array: const arr = [1, 2, 5, 10];
How I can transform it to const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]?;
A simple way to do it without hard-coding the number of iterations is to get the minimum value from the array and the maximum and then fill the numbers in-between them.
Here's one way to do it
const arr = [1, 2, 5, 10];
var highest = Math.max(...arr);
var minimum = Math.min(...arr);
var output = [];
for(var i = minimum; i <= highest; i++){
output.push(i);
}
console.log(output);
Here's a one liner solution based on Adriani6 answer:
const arr = [1, 2, 5, 10];
var highest = Math.max(...arr);
var minimum = Math.min(...arr);
const newArr = ([...Array(highest+1).keys()]).slice(minimum);
console.log(newArr);
const arr = [1, 2, 5, 10];
for(let i = 1; i <= 10; i++) { // Loop from 1 till 10, including 10
if (!arr.includes(i)) { // If arr does not include 'i'
arr.splice(i - 1, 0, i); // We insert it into the array
// -1, because arrays start at 0
}
}
You could take a nested while statement and splice missing items.
var array = [1, 2, 5, 10],
i = array.length;
while (i--) while (array[i - 1] + 1 < array[i]) array.splice(i, 0, array[i] - 1);
console.log(...array);

Iterate through array by sets of [unknown integer] [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 5 years ago.
Assuming I have an integer n which is greater than 0, and an array like this:
var array = [1, 2, 5, 6, 8, 9, 12, 13, 17...] //random values
How would I iterate through this array, going through and getting values n at a time (and putting it into a 2D array as well)?
If n were 3, for example, I would want a return value of
[[1, 2, 5], [6, 8, 9], [12, 13, 17]...]
And the code would be like this:
var array = [];
for (var i = 0; i < array.length; i += 3) {
var first = array[i];
var second = array[i+1];
var third = array[i+2];
array.push([
first, second, third
]);
}
Problem with this is that I have fixed values to get my objects by (the i, i+1, etc.)
If I have an unknown integer, then incrementing right up to n will not work.
How would I go about achieving this?
Use slice to take chunks and go through the array:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const partition = (n, arr) => {
const result = [];
let i = 0;
while(i < arr.length) {
result.push(arr.slice(i, i + n));
i = i + n;
}
return result;
};
console.log(partition(1, arr));
console.log(partition(2, arr));
console.log(partition(3, arr));
console.log(partition(4, arr));

Convert a 1D array to 2D array [duplicate]

This question already has answers here:
Convert simple array into two-dimensional array (matrix)
(19 answers)
Closed 8 years ago.
I am working on a program where I have to read the values from a textfile into an 1D array.I have been succesfull in getting the numbers in that 1D array.
m1=[1,2,3,4,5,6,7,8,9]
but I want the array to be
m1=[[1,2,3],[4,5,6],[7,8,9]]
You can use this code :
const arr = [1,2,3,4,5,6,7,8,9];
const newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr);
http://jsfiddle.net/JbL3p/
Array.prototype.reshape = function(rows, cols) {
var copy = this.slice(0); // Copy all elements.
this.length = 0; // Clear out existing array.
for (var r = 0; r < rows; r++) {
var row = [];
for (var c = 0; c < cols; c++) {
var i = r * cols + c;
if (i < copy.length) {
row.push(copy[i]);
}
}
this.push(row);
}
};
m1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
m1.reshape(3, 3); // Reshape array in-place.
console.log(m1);
.as-console-wrapper { top:0; max-height:100% !important; }
Output:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
JSFiddle DEMO
I suppose you could do something like this... Just iterate over the array in chunks.
m1=[1,2,3,4,5,6,7,8,9];
// array = input array
// part = size of the chunk
function splitArray(array, part) {
var tmp = [];
for(var i = 0; i < array.length; i += part) {
tmp.push(array.slice(i, i + part));
}
return tmp;
}
console.log(splitArray(m1, 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Obviously there is no error checking, but you can easily add that.
DEMO
There are so many ways to do the same thing:
var m = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var n = [];
var i = 0;
for (l = m.length + 1; (i + 3) < l; i += 3) {
n.push(m.slice(i, i + 3));
}
// n will be the new array with the subarrays
The above is just one.

Categories