I'm trying to solve the following exercise:
Reverse an array without using the reverse method, without using a
second array, and without duplicating any of the values.
I've thought about making the array an object and then updating the array from the end to the beginning but I figured you can just update it as well.
Tried something simple like:
function reverseArray(array) {
for (var i = 0; i < array.length; i++) {
// var elem = array.shift();
var elem = array.shift()
array.push(elem)
}
return array
}
array = ['a', 'b','c','d','e'];
reverseArray(array);
But that doesn't really change it. Any advice or explanation on how to do this?
With ES6 syntax you don't need to copy a value into a temporary variable (is that what the last requirement is about?).
function reverse(arr) {
for(let i = 0, j = arr.length-1; i < j; i++, j--)
[arr[i], arr[j]] = [arr[j], arr[i]];
}
const arr = ['a','b','c','d','e'];
reverse(arr);
console.log(arr);
One may argue that arrays are created here (if engines don't optimise this away), just like splice also creates an array (as its return value).
array = ['a', 'b', 'c', 'd', 'e'];
console.log(array);
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var item = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = item;
}
console.log(array);
Here is a minimal approach. Given var arr = [1,2,3,4], this loop will mutate arr to [4,3,2,1]:
for (var i = 0; i < arr.length - 1; i++) {
arr.splice(i, 0, arr.pop());
}
The following will work reverse an array without using the reverse method. It works by swapping the first and last elements, then the second and second-to-last elements, then the third and third-to-last elements, etc until the i is no longer less than (<) than j.
function reverse(arr) {
for(var i = 0, j = arr.length-1; i < j; i++, j--) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
};
var reversed = reverse(['a','b','c','d','e']);
console.log(reversed);
https://jsfiddle.net/pa2fqa8n/1/
a = ['a', 'b', 'c', 'd', 'e'];
for(var i = 0; i < a.length-1; i++){
for(var j = 0; j < a.length-i-1; j++){
var k = a[j];
a[j] = a[j+1];
a[j+1] = k;
}
}
First iteration of inner loop moves the first element to the end, and the rest of the elements forward once. Each following iteration does the same thing, but 1 less than the previous iteration.
I had to use a swap variable, does that violate "without duplicating any of the values"?
var test1 = [2, '5', 6, 'a', 'Z'];
var test2 = [2, '5', false, 'a', 'Z', {a: 'whatevs'}];
console.log('test1 before', JSON.stringify(test1));
console.log('test2 before', JSON.stringify(test2));
reversarooni(test1);
reversarooni(test2);
console.log('test1 after', JSON.stringify(test1));
console.log('test2 after', JSON.stringify(test2));
function reversarooni(inputArray) {
var index = 0;
var len = inputArray.length;
for(; index < len / 2; index++) {
var swap = inputArray[index];
inputArray[index] = inputArray[(len - 1) - index];
inputArray[(len - 1) - index] = swap;
}
}
Here's how, without copies, temporary arrays or variables to hold values, or using Array.reverse().Modifying the array in place
function reverseArray(array) {
var len = array.length;
for (var i=len,j=-1; j++,i--;) array.unshift( array[len-1-i+(j)] );
array.length = len;
}
var array = ['a', 'b','c','d','e'];
reverseArray(array);
console.log(array);
It inserts the values backwards into the beginning of the array, pushing the old values to the end, and then slicing them of by resetting the arrays length after the iteration has completed.
You could use a spread syntax ..., rest parameters ... and return the swapped items with a recursive and functional approach.
const
_ = (...a) => a,
rev = (a, ...rest) => rest.length ? _(...rev(...rest), a) : _(a),
reverseArray = array => rev(...array);
console.log(reverseArray(['a', 'b', 'c', 'd', 'e']));
console.log(reverseArray(['a']));
console.log(reverseArray(['a', 'b']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
function reverseArray(a) {
const halfLength = a.length / 2;
for (let i = 0; i< halfLength; i++){
const start = a[i]
a[i] = a[a.length-i-1]
a[a.length-i-1] = start
}
return a;
}
function printReverse(array) {
for (i = array.length-1; i > -1; i--) {
console.log(array[i]); //4,3,2,1
}
}
printReverse([1, 2, 3, 4]);
This worked for me.
Related
Please help me to solve this leetcode problem using javascript as I am a beginner and dont know why this code is not working
Ques: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
var findDisappearedNumbers = function (nums) {
var numLength = nums.length;
nums.sort(function (a, b) { return a - b });
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
}
}
for (var k = 0; k < nums.length; k++) {
for (var j = 1; j <= numLength; j++) {
if (nums[k] !== j) {
return j;
}
}
}
};
if there is any error in my code please let me know;
i have done the following thing
first i have sorted the array in ascending order
then i have cut all the duplicate elements
then i have created loop that will check if nums[k] !== j ;
and it will return j which is the missing number;
for example this is the testcase [4,3,2,7,8,2,3,1]
first my code will sort this in ascending order [1,2,2,3,3,4,7,8]
then it will remove all duplicate elements and it will return [1,2,3,4,,7,8]
and then it will check nums[k] is not equal to j and it will print j
I think it'd be easier to create a Set of numbers from 1 to n, then just iterate through the array and delete every found item from the set:
var findDisappearedNumbers = function(nums) {
const set = new Set();
for (let i = 0; i < nums.length; i++) {
set.add(i + 1);
}
for (const num of nums) {
set.delete(num);
}
return [...set];
};
console.log(findDisappearedNumbers([4,3,2,7,8,2,3,1]));
To fix your existing code, I'm not sure what the logic you're trying to implement in the lower section, but you can iterate from 1 to numLength (in the outer loop, not the inner loop) and check to see if the given number is anywhere in the array. Also, since you're mutating the array with splice while iterating over it in the upper loop, make sure to subtract one from i at the same time so you don't skip an element.
var findDisappearedNumbers = function(nums) {
var numLength = nums.length;
nums.sort(function(a, b) {
return a - b
});
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
i--;
}
}
const notFound = [];
outer:
for (var j = 1; j < numLength; j++) {
for (var k = 0; k < nums.length; k++) {
if (nums[k] === j) {
continue outer;
}
}
notFound.push(j);
}
return notFound;
};
console.log(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]));
#CertainPerformance certainly cracked it again using the modern Set class. Here is a slighly more conservative approach using an old fashioned object:
console.log(missingIn([4,3,2,7,8,2,3,1]));
function missingIn(arr){
const o={};
arr.forEach((n,i)=>o[i+1]=1 );
arr.forEach((n) =>delete o[n] );
return Object.keys(o).map(v=>+v);
}
My solution for the problem to find the missing element
var findDisappearedNumbers = function(nums) {
const map={};
const result=[];
for(let a=0;a<nums.length;a++){
map[nums[a]]=a;
}
for(let b=0;b<nums.length;b++){
if(map[b+1]===undefined){
result.push(b+1)
}
}
return result;
};
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
I have an array that looks like this
const x = ['A','B','C','D','E']
I want to have an elegant function that would shuffle the content of the array but keeps the first or the last element fixed. Something like customShuffle(x) which will shuffle the array but ensures that the element "A" will be in the first position and the element "E" will be at the last position. All other elements are shuffled.
If the first and last elements of the array always stay in that same place, you can apply a normal shuffling algorithm, like a modern variation of Fisher and Yates', skipping those positions:
function customShuffle(arr) {
if (arr.length < 3) {
return arr;
}
// Note the -2 (instead of -1) and the i > 1 (instead of i > 0):
for (let i = arr.length - 2; i > 1; --i) {
const j = 1 + Math.floor(Math.random() * i);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
console.log(customShuffle([1, 2, 3, 4, 5]).join(', '));
console.log(customShuffle(['A', 'B', 'C', 'D', 'E']).join(', '));
.as-console-wrapper {
max-height: 100vh;
}
Otherwise, if you want to choose the first and last elements, as you pointed out in your original question, you can do something like this:
Find the index of the elements you want to have in the first and last positions first: firstIndex and lastIndex.
If those elements exist (they might not be present), remove them from the array.
Apply a shuffling algorithm to the remaining elements (there's no need to also shuffle first and last).
Add the first and last elements back into their place, if you need to.
function customShuffle(arr, first, last) {
// Find and remove first and last:
const firstIndex = arr.indexOf(first);
if (firstIndex !== -1) arr.splice(firstIndex, 1);
const lastIndex = arr.indexOf(last);
if (lastIndex !== -1) arr.splice(lastIndex, 1);
// Normal shuffle with the remainign elements using ES6:
for (let i = arr.length - 1; i > 0; --i) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
// Add them back in their new position:
if (firstIndex !== -1) arr.unshift(first);
if (lastIndex !== -1) arr.push(last);
return arr;
}
console.log(customShuffle([1, 2, 3, 4, 5], 5, 1).join(', '));
console.log(customShuffle(['A', 'B', 'C', 'D', 'E'], 'E', 'C').join(', '));
console.log(customShuffle([1, 2, 3, 4, 5], 10, 20).join(', '));
.as-console-wrapper {
max-height: 100vh;
}
Using the shuffle algorithm from How to randomize (shuffle) a JavaScript array?
You can extend it like this:
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function customShuffle(array, first, last) {
if (first) {
if (last) {
const updatedArray = shuffle(array).filter(item => item !== first && item !== last);
return [first, ...updatedArray, last];
}
const updatedArray = shuffle(array).filter(item => item !== first);
return [first, ...updatedArray];
}
return shuffle(array);
}
You could first generate new shuffled array and then check if first and last arguments are provided and take those elements and place them on first and last position.
const x = ['A', 'B', 'C', 'D', 'E']
function shuffle(arr, first, last) {
const newArr = arr.reduce((r, e, i) => {
const pos = parseInt(Math.random() * (i + 1))
r.splice(pos, 0, e)
return r;
}, []);
if (first) newArr.unshift(newArr.splice(newArr.indexOf(first), 1)[0]);
if (last) newArr.push(newArr.splice(newArr.indexOf(last), 1)[0])
return newArr
}
console.log(shuffle(x))
console.log(shuffle(x, "A", "E"))
You can do it like this. first and last params are optional.
Check if first is passed and if it is in the array. If so, then remove it from the array. Do the same for the last. Shuffle indices of the remaining array. Recreate new array based on the shuffled indices, as well as first and last arguments.
const shuffle = (arr, first, last) => {
let firstIn = false;
let lastIn = false;
if (first && arr.includes(first)) {
arr.splice(arr.indexOf(first), 1);
firstIn = true;
}
if (last && arr.includes(last)) {
arr.splice(arr.indexOf(last), 1);
lastIn = true;
}
const len = arr.length;
const used = [];
while (used.length !== len) {
let r = Math.floor(Math.random() * len);
if (!used.includes(r)) { used.push(r); }
}
const newArr = [];
if (first && firstIn) { newArr.push(first); }
for (let i = 0; i < len; i++) {
newArr.push(arr[used[i]]);
}
if (last && lastIn) { newArr.push(last); }
return newArr;
}
let arr = ['A', 'B', 'C', 'D', 'F'];
arr = shuffle(arr);
console.log(arr);
arr = shuffle(arr, 'A');
console.log(arr);
arr = shuffle(arr, 'A', 'B');
console.log(arr);
shuffle(arr); will shuffle the whole array.
arr = shuffle(arr, 'A'); will move A to the front and shuffle the rest.
arr = shuffle(arr, 'A', 'B'); will move A to the front, B to the end, and shuffle the rest.
Word of caution: while this approach is not in-place, it will still mutate the original array, because of the splice method.
Try something like this. It keeps the first and last elements in place without explicitly defining their values, and builds a new array with the other elements shuffled randomly.
const x = ['A','B','C','D','E'];
const shuffledArray = customShuffle(x);
console.log(shuffledArray);
function customShuffle(arr) {
let newArray = [];
const first = arr[0];
const last = arr[arr.length-1];
//First, remove the 'first' and 'last' values from array:
for(let i=0; i<arr.length; i++){
if(arr[i] == first || arr[i] == last){
arr.splice(i, 1);
}
}
//Next, add values to the new array at random:
for(let i=0; i<arr.length; i++){
const indexToRemove = Math.floor( Math.random() * arr.length );
const value = arr[indexToRemove];
arr.splice(indexToRemove, 1);
newArray.push(value);
}
//Last, add in the 'first' and 'last' values:
newArray.unshift(first);
newArray.push(last);
return newArray;
}
Please try the following simple solution.This will shuffle all the elements other than the first and the last element of the array (jsfiddle):
const x = ['A', 'B', 'C', 'D', 'E'];
CustomShuffle(x);
function CustomShuffle(x) {
//shuffle the elements in between first and the last
var max = x.length - 2;
var min = 1;
for (var i = max; i >= min; i--) {
var randomIndex = Math.floor(Math.random() * (max - min + 1)) + min;
var itemAtIndex = x[randomIndex];
x[randomIndex] = x[i];
x[i] = itemAtIndex;
}
alert(x);
}
In case first and last elements are not in place beforehand, you may try the following (jsfiddle):
const x = ['A', 'B', 'C', 'D', 'E'];
CustomShuffle(x, first = "B", last = "A");
function CustomShuffle(x, first, last) {
//position first element correctly
var indexToSwap = x.indexOf(first);
if (indexToSwap != 0) {
x = SwapValuesAtIndices(x, indexToSwap, 0);
}
//position last element correctly
indexToSwap = x.indexOf(last);
if (indexToSwap != x.length - 1) {
x = SwapValuesAtIndices(x, indexToSwap, x.length - 1);
}
//randomly shuffle the remaining elements in between
var max = x.length - 2;
var min = 1;
for (var i = max; i >= min; i--) {
var randomIndex = Math.floor(Math.random() * (max - min + 1)) + min;
var itemAtIndex = x[randomIndex];
x[randomIndex] = x[i];
x[i] = itemAtIndex;
}
alert(x);
}
function SwapValuesAtIndices(array, firstIndex, secondIndex) {
var temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
return array;
}
Further reading:
Shuffling an array
Generating a random number in a given
range
Swapping elements
You can use this function which uses the modern version of the Fisher–Yates shuffle algorithm to shuffle the sub-array x.slice(1, x.length - 1), which is x with the exclusion of the first and last elements, then adds them back to the shuffled sub-array:
const x = ['A','B','C','D','E'];
function customShuffle(x) {
var y = x.slice(1, x.length - 1);
var j, t, i;
for (i = y.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
t = y[i];
y[i] = y[j];
y[j] = t;
}
return [x[0]].concat(y).concat(x[x.length-1]);
}
console.log(customShuffle(x));
console.log(customShuffle(x));
console.log(customShuffle(x));
console.log(customShuffle(x));
Because you asked for elegant, I like to implement a more functional style of programming here. The code below does what you want. You supple the shuffle function with your array, the max number of times you want it shuffled (the higher the number, the better the shuffle is), and true to keep the first element in place, false to keep the last.
function shuffle(array, maxTimes, first) {
var temp = (first) ? array.reverse().pop() : array.pop();
Array.from(
Array(Math.round(Math.random()*maxTimes))
.keys()).forEach(val => array = array.reduce((acc,val) =>
(Math.random() > 0.5) ? acc.concat([val]) : [val].concat(acc),[]));
return (first) ? [temp].concat(array.reverse()) : array.concat([temp]);
}
Example usage:
shuffle(['A','B','C','D','E'], 10, true);
Output: ["A", "C", "D", "B", "E"]
I hope this is what you're looking for and answers your question.
Edit
Turns out you can get the shuffle logic all in one line (when removing the unnecessary newlines). When you add the two lines to retain the first or last character, you can essentially create this function with three lines of code.
function SpecialShuffle(MyArray)
{
var newArray = [];
var counter= 1;
for(var i = MyArray.length-1 ; i>-1 ; i--)
{
if(i == MyArray.length)
{
newArray[i] = MyArray[i]
}
else if(i == 0 )
{
newArray[i]=MyArray[i];
}
else
{
newArray[counter] = MyArray[i];
counter++;
}
}
return newArray;
}
I'm trying to solve the following exercise:
Reverse an array without using the reverse method, without using a
second array, and without duplicating any of the values.
I've thought about making the array an object and then updating the array from the end to the beginning but I figured you can just update it as well.
Tried something simple like:
function reverseArray(array) {
for (var i = 0; i < array.length; i++) {
// var elem = array.shift();
var elem = array.shift()
array.push(elem)
}
return array
}
array = ['a', 'b','c','d','e'];
reverseArray(array);
But that doesn't really change it. Any advice or explanation on how to do this?
With ES6 syntax you don't need to copy a value into a temporary variable (is that what the last requirement is about?).
function reverse(arr) {
for(let i = 0, j = arr.length-1; i < j; i++, j--)
[arr[i], arr[j]] = [arr[j], arr[i]];
}
const arr = ['a','b','c','d','e'];
reverse(arr);
console.log(arr);
One may argue that arrays are created here (if engines don't optimise this away), just like splice also creates an array (as its return value).
array = ['a', 'b', 'c', 'd', 'e'];
console.log(array);
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var item = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = item;
}
console.log(array);
Here is a minimal approach. Given var arr = [1,2,3,4], this loop will mutate arr to [4,3,2,1]:
for (var i = 0; i < arr.length - 1; i++) {
arr.splice(i, 0, arr.pop());
}
The following will work reverse an array without using the reverse method. It works by swapping the first and last elements, then the second and second-to-last elements, then the third and third-to-last elements, etc until the i is no longer less than (<) than j.
function reverse(arr) {
for(var i = 0, j = arr.length-1; i < j; i++, j--) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
};
var reversed = reverse(['a','b','c','d','e']);
console.log(reversed);
https://jsfiddle.net/pa2fqa8n/1/
a = ['a', 'b', 'c', 'd', 'e'];
for(var i = 0; i < a.length-1; i++){
for(var j = 0; j < a.length-i-1; j++){
var k = a[j];
a[j] = a[j+1];
a[j+1] = k;
}
}
First iteration of inner loop moves the first element to the end, and the rest of the elements forward once. Each following iteration does the same thing, but 1 less than the previous iteration.
I had to use a swap variable, does that violate "without duplicating any of the values"?
var test1 = [2, '5', 6, 'a', 'Z'];
var test2 = [2, '5', false, 'a', 'Z', {a: 'whatevs'}];
console.log('test1 before', JSON.stringify(test1));
console.log('test2 before', JSON.stringify(test2));
reversarooni(test1);
reversarooni(test2);
console.log('test1 after', JSON.stringify(test1));
console.log('test2 after', JSON.stringify(test2));
function reversarooni(inputArray) {
var index = 0;
var len = inputArray.length;
for(; index < len / 2; index++) {
var swap = inputArray[index];
inputArray[index] = inputArray[(len - 1) - index];
inputArray[(len - 1) - index] = swap;
}
}
Here's how, without copies, temporary arrays or variables to hold values, or using Array.reverse().Modifying the array in place
function reverseArray(array) {
var len = array.length;
for (var i=len,j=-1; j++,i--;) array.unshift( array[len-1-i+(j)] );
array.length = len;
}
var array = ['a', 'b','c','d','e'];
reverseArray(array);
console.log(array);
It inserts the values backwards into the beginning of the array, pushing the old values to the end, and then slicing them of by resetting the arrays length after the iteration has completed.
You could use a spread syntax ..., rest parameters ... and return the swapped items with a recursive and functional approach.
const
_ = (...a) => a,
rev = (a, ...rest) => rest.length ? _(...rev(...rest), a) : _(a),
reverseArray = array => rev(...array);
console.log(reverseArray(['a', 'b', 'c', 'd', 'e']));
console.log(reverseArray(['a']));
console.log(reverseArray(['a', 'b']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
function reverseArray(a) {
const halfLength = a.length / 2;
for (let i = 0; i< halfLength; i++){
const start = a[i]
a[i] = a[a.length-i-1]
a[a.length-i-1] = start
}
return a;
}
function printReverse(array) {
for (i = array.length-1; i > -1; i--) {
console.log(array[i]); //4,3,2,1
}
}
printReverse([1, 2, 3, 4]);
This worked for me.
I am doing freecodecamp's Bonfire:Chunky Monkey. I almost have the solution, but I can't figure it out why it isn't working. So my question is: "Why does this return [['a', 'b']], instead of [['a','b'],['c','d']]?
function chunk(arr, size) {
var array = [];
var tmp = [];
for(var i = 0; i < Math.floor(arr.length/size); i++)
{
for(var j = 0; j < size; j++)
{
tmp.push(arr[j]);
}
array.push(tmp);
tmp = [];
arr.splice(0,size);
}
return array;
}
chunk(['a', 'b', 'c', 'd'], 2);
Because you are altering the length of arr within the loop. As a result, the outer loop only runs once. You need to cache this before you alter it:
function chunk(arr, size) {
var array = [];
var tmp = [];
// save this, otherwise the 2nd iteration will not run at all
// because the new array length will be 2, making half of that 1
var iter = Math.floor(arr.length / size);
for (var i = 0; i < iter; i++) {
for (var j = 0; j < size; j++) {
tmp.push(arr[j]);
}
array.push(tmp);
tmp = [];
arr.splice(0, size);
}
return array;
}
You are modifying the length of arr on each iteration preventing it from executing the second time.
Besides, one loop is enough.
function chunk(arr, size) {
var array = [];
for(var i = 0; i < arr.length; i += size) {
array.push(arr.slice(i, i + size));
}
return array;
}
chunk(['a', 'b', 'c', 'd'], 2);
Another approach:
function chunk(arr, size) {
var array = [];
var tmp = [];
var aux = 0;
for(var i = 0; i < Math.ceil(arr.length/size); i++)
{
for(var j = aux; j < aux + size; j++)
{
arr[j] != undefined?tmp.push(arr[j]):false;
}
aux = aux + size;
array.push(tmp);
tmp = [];
}
return array;
}
console.log(chunk(['a', 'b', 'c', 'd', 'e', 'f'], 2));
PS: It works with even and odd number of elements in the array.
Plenty of answers with working codes, so I just answer the why.
You thought the outer loop iterates twice, because Math.floor(arr.length/size) is 2 at the beginning:
for(var i = 0; i < Math.floor(arr.length/size); i++) {
// ....
}
However, arr is chunked in the first iteration:
arr.splice(0,size); // arr is ['c', 'd'] after this step
For the second iteration, i becomes 1 and Math.floor(arr.length/size) is actually Math.floor(['c', 'd']/2), the check fails and the loop exits. So there isn't a second iteration.
Configurable chunk size example with a loop.
function chunk(arr, chunkSize) {
var array = [];
for (var index = 0, arrLen; index < chunkSize; index++) {
arrLen = arr.length;
if (arrLen >= chunkSize) {
array[index] = arr.splice(0, chunkSize === 1 ? arrLen : chunkSize);
} else if (arrLen > 0) {
array[index] = arr.splice(0, arrLen);
}
}
return array;
}
var result = chunk(['a', 'b', 'c', 'd'], 1);
console.log(result);
I have a javascript array of values [A,B,C,D,E.....] that i need to split with this syntax:
[ [A, B], [C, D], [E, F] ]
and so on (it will be always a pair).
So it should be a loop that returns a string.
I've tried to do like so, and it's almost what i wanted:
text = '['+array[0]+','+array[1]+']';
for (index = 2; index < array.length; index++) {
text += '['+array[index]+','+array[index+1]+']';
console.log(text);
}
I get
[10:00,15:45][18:30,20:00]
[10:00,15:45][18:30,20:00][20:00,undefined]
instead i need to get only this:
[10:00,15:45][18:30,20:00]
Could try making text an actual array and pushing pairs in, like so
var orig=['A','B','C','D','E','F'];
var text=[];
for (index = 0; index < orig.length-1; index+=2) {
text.push([orig[index],orig[index+1]]);
console.log(JSON.stringify(text));
}
Here's a small method for grouping array elements. You can just check that your inner arrays have a length of 2 afterwards, if you only care about pairs.
if (!Array.prototype.group) {
Array.prototype.group = function (length) {
var a = this.slice(), r = [];
length = length || 1;
while (a.length > 0) {
r.push(a.splice(0, length));
}
return r;
};
}
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].group(2);
console.log(arr);
A version for if you want to discard a final group that doesn't match your expected length.
if (!Array.prototype.group) {
Array.prototype.group = function (length, req) {
var a = this.slice(), r = [], h;
length = length || 1;
while (a.length > 0) {
h = a.splice(0, length);
if (!req || h.length === length) {
r.push(h);
}
}
return r;
};
}
var arr = ['an', 'odd', 'number', 'of', 'elements'].group(2, true);
console.log(arr)
Something in the lines of:
var groupArray = function(arr){
var groupedArray = [];
for(var i = 0, len = arr.length; i < len; i += 2){
groupedArray.push([arr[i], arr[i + 1]]);
}
return groupedArray;
};
This obviously only works for arrays with an even number of elements. If you need the function to work with arrays with an odd number of elements, too, you need to acomodate for that.