I have an array like this:
arrayA = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2];
I need to get separated numbers in groups like this:
arrayB = [1234,5678,9123,4567,8912];
As you can see its the same arrayA but in groups of 4 values that are now new numbers.
I was able to make it work with a bug like this: arrayB=[undefined1234,undefined5678];
with this code:
for (var i = 0; i < 20; i++) {
if (i/4== n+1){
arrayB[n] = temp;
n++;
}
temp += arrayA[i];
}
And thats it. I understand the bug, it is because of that += but am not sure how to do this any other way.
this code will do that trick
var arrayA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2,3,4];
var arrayB = [];
for (var x = 0; x < arrayA.length; x += 4) {
arrayB.push(arrayA.slice(x, x + 4).join(''));
}
console.log(arrayB);
Update
Millie has raised a fair point. if you need numbers in the result array, use following statement in for loop
arrayB.push(parseInt(arrayA.slice(x, x + 4).join('')));
Try setting temp to "" both before the loop starts and after each time you assign to arrayB (and when you make that assignment, turn the string in step into an integer). And you may need to make a final assignment to arrayB after the for loop finishes.
I would do it like this:
arrayA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2];
temp = arrayA.join('');
count = 4;
grouped = [];
max = temp.length / count;
for (i = 0; i < max; i++) {
grouped.push(parseInt(temp.substr(i * 4, 4)));
}
console.log(grouped);
Little numbers to strings conversion, and returning of numbers. :)
Demo: http://jsfiddle.net/hue0a1wb/
Related
I'm currently working on an array function that converts subarrays of consecutive numbers into strings denoting that range of numbers — for example, this array...
[1, 2, 3, 6, 8, 10, 11, 12, 15, 18]
...would become this array:
["1-3", 6, 8, "10-12", 15, 18]
I've been able to develop a function that mostly works, but I've encountered a weird error where all the elements past the final range of numbers spliced into the array are completely deleted. For example, the test array above actually becomes this:
["1-3", 6, 8, "10-12"]
This is the code I've written so far. It's not super pretty yet, but as I mentioned above, it gets the job done right up until the very end:
let testArray = [1, 2, 3, 6, 8, 10, 11, 12, 15, 18];
for (i = 0; i < testArray.length; i++) {
let consecutives = [];
consecutives.push(testArray[i]);
let j = i + 1;
while (j < testArray.length) {
if (testArray[j] == (testArray[j - 1] + 1)) {
consecutives.push(testArray[j]);
j++;
} else {
break;
}
}
if (consecutives.length > 2) {
let range = String(testArray[i]) + "-" + String(testArray[j - 1]);
console.log(testArray);
console.log(testArray[i]);
console.log(testArray[j]);
testArray.splice(i, j, range);
}
}
console.log(testArray);
These are the console logs output by that code:
Array(10) [ 1, 2, 3, 6, 8, 10, 11, 12, 15, 18 ]
1
6
Array(8) [ "1-3", 6, 8, 10, 11, 12, 15, 18 ]
10
15
Array(4) [ "1-3", 6, 8, "10-12" ]
I initially figured this was caused by a mix-up with array indexes, but playing around with the index-1s hasn't fixed the problem yet. Has anyone else ever had a similar issue with JavaScript's splicing, and if so, how were you able to get it working?
The problem lies in one line of code:
testArray.splice(i, j, range);
According to the MDN, the second argument specifies how many elements in the array to delete.
deleteCount
An integer indicating the number of elements in the array to remove from start.
However, the code defines this argument as the index of the last array to remove from:
let j = i + 1;
The solution is to get the difference between i and j before passing it to splice:
testArray.splice(i, j - i, range);
When you do:
testArray.splice(i, j, range);
You are forgetting that j is the right limit index of the array that you want to erase, so you need to subtract i that is the left limit:
testArray.splice(i, j - i, range);
let testArray = [1, 2, 3, 6, 8, 10, 11, 12, 15, 18];
for (i = 0; i < testArray.length; i++) {
let consecutives = [];
consecutives.push(testArray[i]);
let j = i + 1;
while (j < testArray.length) {
if (testArray[j] == (testArray[j - 1] + 1)) {
consecutives.push(testArray[j]);
j++;
} else {
break;
}
}
if (consecutives.length > 2) { // doesn´t it should be > 1 ??
let range = String(testArray[i]) + "-" + String(testArray[j - 1]);
console.log(testArray);
console.log(testArray[i]);
console.log(testArray[j]);
testArray.splice(i, j - i, range);
}
}
console.log(testArray);
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);
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));
What is an efficient way of looping through two arrays to produce an alternating output? In JavaScript.
If I have two arrays like this:
var oddNumbers = [1, 3, 5, 7, 9]
var evenNumbers = [2, 4, 6, 8, 10, 12, 14]
NB: The arrays may not be the same length
How can I get the following output?
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14
I would have thought this would work:
if (oddNumber.length > evenNumbers.length) {
var large = oddNumbers;
} else {
var large = evenNumbers;
}
for(var i = 0; i < large.length; i++){
if (evenNumbers.length >= i && oddNumbers.length >= i) {
console.log(oddNumbers[i] + ", " + evenNumbers[0]);
} elseif (evenNumbers.length >= i) {
console.log(evenNumbers[0]);
} else {
console.log(oddNumbers[0]);
}
}
But it's pretty messy, any better way of approaching this?
NOTE: These may not necessarily be in a numerical order, or in fact numbers
I would rather do it as follows if you just want to output them:
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
for (var i=0, j=0; i < oddNumbers.length || j < evenNumbers.length;) {
if (i < oddNumbers.length) {
console.log(oddNumbers[i++]);
}
if (j < evenNumbers.length) {
console.log(evenNumbers[j++]);
}
}
If you want to get the merge result as another array you can replace console.log with result.push to push result values on an array named result as follows:
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var result = [];
for (var i=0, j=0; i < oddNumbers.length || j < evenNumbers.length;) {
if (i < oddNumbers.length) {
result.push(oddNumbers[i++]);
}
if (j < evenNumbers.length) {
result.push(evenNumbers[j++]);
}
}
console.log(result);
This way you iterate both arrays as long as one of them has an element that we haven't visited yet and also prevents iterating over the same index of same array twice. Please note that I used increment in if blocks to save 2 lines of code. You can also move them to the for loop since they won't break if statements.
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var oLength = oddNumbers.length;
var eLength = evenNumbers.length;
var n = oLength > eLength ? oLength : eLength;
var rez=[];
for(i=0;i<n;i++){
if (i< oLength) rez.push(oddNumbers[i])
if (i<eLength) rez.push(evenNumbers[i])
}
console.log(rez);
var odd = ["A", "C","E","G"];
var even = ["B","D","F"];
var rez=[];
for(i=0;i<(odd.length > even.length ? odd.length : even.length);i++){
if (i< odd.length) rez.push(odd[i])
if (i<even.length) rez.push(even[i])
}
console.log(rez);
The following function accepts two arrays and returns their interleaved values as a new array:
function interleaveArrays(a, b) {
var array = [],
limit = a.length >= b.length ? a.length : b.length;
index = 0;
while (index < limit) {
a[index] && array.push(a[index]);
b[index] && array.push(b[index]);
index += 1;
}
return array;
}
Calling the function like so:
var oddNumbers = [1, 3, 5, 7, 9],
evenNumbers = [2, 4, 6, 8, 10, 12, 14];
console.log(interleaveArrays(oddNumbers, evenNumbers));
Yields:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14 ]
You can then output this in your preferred manner; e.g:
var interleaved = interleaveArrays(oddNumbers, evenNumbers);
// as a loop
interleaved.forEach(function (n) {
console.log(n);
})
// or as a string
console.log(interleaved.join(', '));
// etc.
Hope this helps :)
I'd do something like this.
large = (oddNumber.length >= evenNumbers.length) ? oddNumbers : evenNumbers;
small = (oddNumber.length < evenNumbers.length) ? oddNumbers : evenNumbers;
for(var i = 0; i < large.length; i++){
if(small.length <= i + 1){
console.log(small[i] + ", "+ large[i]);
}
else {
console.log(large[i]);
}
}
A long-hand example of how it can be done. The code can be shrunk for a final solution. The basic principle I'm using is to even out the lengths to take care of the alternating then tag on the tail
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var oLength = oddNumbers.length;
var eLength = evenNumbers.length;
var oTemp, eTemp, remainder;
if(oLength > eLength) {
eTemp = evenNumbers;
oTemp = oddNumbers.slice(0, eLength);
remainder = oddNumbers.slice(eLength);
} else if (eLength > oLength) {
eTemp = evenNumbers.slice(0, oLength);
oTemp = oddNumbers;
remainder = evenNumbers.slice(oLength);
} else {
eTemp = evenNumbers;
oTemp = oddNumbers;
remainder = [];
}
var final = [];
for(var i=0; i < eTemp.length; i++) {
final.push(oTemp[i]);
final.push(eTemp[i]);
}
final = final.concat(remainder);
alert(final);
I would simply merge the two array and sort it
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var mergedArr=oddNumbers.concat(evenNumbers );
console.log(mergedArr.sort(function(a,b){return a-b;}));
See No loop.. No hassle. Very Simple
There will be an extra , on the screen. Add an if statement if you don't want that
for(var i = 0; i < large.length; i++){
if(i<evenNumbers.length)
console.log(evenNumbers[i]+",");
if(i<oddNumber.length)
console.log(evenNumbers[i]+",");
}
try this it will work always either number Array or String Array:
var oddNumber = [1, 3, 5, 7, 9]
var evenNumber = [2, 4, 6, 8, 10, 12, 14]
var margedNumbers = oddNumber.concat(evenNumber);
console.log("before: "+margedNumbers);
margedNumbers.sort(function(a, b){return a-b})
console.log("after: "+margedNumbers)
My solution
var oddNumbers = [1, 3, 5, 7, 9]
var evenNumbers = [2, 4, 6, 8, 10, 12, 14]
var extraElements = (oddNumbers.length > evenNumbers.length) ? oddNumbers.slice(evenNumbers.length) : evenNumbers.slice(oddNumbers.length);
var finalArr = [];
var small = (oddNumbers.length < evenNumbers.length) ? oddNumbers : evenNumbers;
small.forEach((each, index) => {
// merge elements in desired order
finalArr.push(oddNumbers[index]);
finalArr.push(evenNumbers[index]);
})
finalArr = finalArr.concat(extraElements);
alert(finalArr);
Extract the extra elements which makes both array of same length. Then, in a simple iteration, push elements from both array with same index.
I am trying to solve this coding challenge and want to know why my code isn't working. Please let me know what the problem is and suggest an alternative solution.
Here is the question:
Create a function called 'reversedLooper' that when passed an array will loop through it backwards and subtract 2 from the last element, 1 from the second to last, 0 from to the third to last, add one to the fourth to last, add 2 to the fifth to last, etc. until it reaches the front of the array. Return the list when you are done
Here is my solution
var arr = [2, 3, 3, 5, 7, 19];
var difference = [];
var arr3 = [];
//the function below is working correctly in the way I intend...
function arrayCreator (arr3) {
var i;
for(i = arr.length - 3; i >= -2; i--) {
arr3.push(i);
}
return arr3;
}
function reversedLooper (arr) {
var i;
for(i=0; i< arr.length; i++) {
var pusher = arr[i] - arr3[i];
difference.push(pusher);
}
return difference;
}
console.log(reversedLooper(arr));
// answer should be [5, 5, 4, 5, 6, 17] in this case
You can use the map() function and reverse() functions:
count = -3;
finalArray = [2, 3, 3, 5, 7, 19]
.reverse()
.map(function (obj) {
count++;
return obj + count;
})
.reverse();
Executing on console gives this:
» count = -3; [2, 3, 3, 5, 7, 19].reverse().map(function (obj) { count++; return obj + count; }).reverse()
« [5, 5, 4, 5, 6, 17]
Snippet
count = -3;
final = [2, 3, 3, 5, 7, 19].reverse().map(function(obj) {
count++;
return obj + count;
}).reverse();
alert(final.join());
You can create an auxiliar variable starting at 2 and decrementing it each iteration, take a look:
function reversedLooper(arr) {
for (var i = arr.length - 1, numToSum = 2; i >= 0; i--, numToSum--) {
arr[i] = arr[i] - numToSum;
}
}
var arr = [2, 3, 3, 5, 7, 19];
reversedLooper(arr);
document.write(arr);
Your code just declare the arrayCreator function without invocation.
And also var pusher = arr[i] + arr3[i]; Edited these two things and your code will work.
change the function reversedLooper to:
function reversedLooper(arr){
var x=-2;
for(var i=arr.length-1;i>=0;i--)
{
arr[i]+=x;
x++;
}
return arr;
}