If I have two immutable lists,
const a = [1,2,3];
const b = [a,b,c,d];
is there an easy way to merge/zip them to result in:
const c = [1,a,2,b,3,c,d];
Is interleave what you are looking for: https://facebook.github.io/immutable-js/docs/#/List/interleave
const a = List([1, 2, 3]);
const b = List([a, b, c, d]);
a.interleave(b)
const a = [1, 2, 3] don't make this array immutable at all. What const does is to guarantee that you're not reassigning a. Pushing or removing items to a don't constitute a reassignment.
This is a real immutable list using immutable.js:
const a = List([1, 2, 3]);
Now.. back to zip.
If you don't want another reference, you can just use a for in the smallest list and build the zip yourself. If you want a ready-made function, you might consider using Underscore's Zip, which does exactly what you want.
If you want to develop a function from scratch then you can use the code below. Basically, the function merges the two array as interleaving the two. Consider 2 arrays, array1 = [1,2,3,4] and array2 = [a,b,c,d,e,f]. Then the below code will output a new array [1,a,2,b,3,c,4,d,e,f]
var i = 0;
var j = 0;
var k = 0;
var len1 = array1.length;
var len2 = array2.length;
var flag = true;
var newArr = [];
//Merge the 2 arrays till the smaller sized array
while (i < len1 && j < len2)
{
if(flag){
newArr[k] = array1[i];
i++; k++;
flag = false;
}
else{
newArr[k] = array2[j];
j++; k++;
flag = true;
}
}
/* Copy the remaining elements of array1[], if there are any */
while (i < len1)
{
newArr[k] = array1[i];
i++;
k++;
}
/* Copy the remaining elements of array2[], if there are any */
while (j < len2)
{
newArr[k] = array2[j];
j++;
k++;
}
console.log(newArr)
Related
I am trying to push numbers in an array into another array in groups of two.
If I have an array [1,4,3,2]; it should return [[1,4],[3,2]];
var arrayPairSum = function(nums) {
var len = nums.length / 2;
var arr = [];
for(var i = 0; i < len; i ++) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);
can anyone see what I need to do to achieve this? I cannot figure it out.
You can use reduce method to achieve this. reduce method accepts a callback method provided on every item in the array.
In the other words, this method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
var array=[1,4,3,2,8];
var contor=array.reduce(function(contor,item,i){
if(i%2==0)
contor.push([array[i],array[i+1]].filter(Boolean));
return contor;
},[]);
console.log(contor);
If you really want to iterate over the array, may skip every second index, so i+=2 ( as satpal already pointed out) :
var arrayPairSum = function(nums) {
var len = nums.length - 1;//if nums.length is not even, it would crash as youre doing nums[i+1], so thats why -1
var arr = [];
for (var i = 0; i < len; i += 2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1, 4, 3, 2]);
The upper one crops away every non pair at the end. If you want a single [value] at the end, may go with
len=nums.length
And check later before pushing
if(i+1<nums.length) newArr.push(nums[i+1]);
You were pretty close. Simply change the length to nums.length and in the loop increment i by 2.
var arrayPairSum = function(nums) {
var len = nums.length - 1;
var arr = [];
for(var i = 0; i < len; i+=2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);
I am working on a code where I need to reverse certain no of elements in an array and rest should remain same. For example is an array has values of 1,2,3,4,5,6 and I have to reverse 4 elements of it then output should be 4,3,2,1,5,6. I am using below code to achieve this but getting error, please suggest.
function reverseArray(n, a) {
var interimArray1 = [];
//var interimArray2=[];
//var finalArray=[];
for (var i < n; i >= 0; i--) {
interimArray1.push[a[i]];
}
for (var i = n; i < a.length; i++) {
interimArray1.push[a[i]];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
The error in your code is that you intend to call the push method on a[i] like so:
interimArray1.push(a[i]);
but instead you write:
interimArray1.push[a[i]];
You make that mistake twice. To give arguments to the push method, you must use round parenthesis ().
With that fixed, you will see that your code works perfectly.
You can use Array#slice, Array#splice as follow.
function partialReverse(arr, num, from = 0) {
var slicedArr = arr.slice(from, num + from);
arr.splice(from, num); // Remove `num` items from array
arr.splice(from, 0, ...slicedArr.reverse()); // Add `num` reversed items
return arr;
}
var arr = [1, 2, 3, 4, 5, 6];
console.log(partialReverse(arr, 4, 0)); // Reverse four items from `arr` starting from 0th index
console.log(partialReverse(arr, 4, 1)); // Reverse four items from `arr` starting from 1st index
Lots of hints but you seem to be missing them. ;-)
You need to assign an initial value to i, so:
for (var i = n; ... )
===========^
Also, you need to use () to call functions, not [], so:
interimArray1.push(a[i]);
==================^====^
Same in the following for block. Otherwise, the code works though it's more verbose than it needs to be.
This is working :
I'm sure there are faster ways of doing it. Also, it will only work for elements at the beginning of the array but you can adjust the function for what you want to achieve.
var reverseArray = function(arr,elementsToReverse) {
var tempArrayRev = [];
var tempArray = [];
for (var i=0;i<arr.length;i++) {
if (i < elementsToReverse) {
tempArrayRev[i] = arr[i];
} else {
tempArray.push(arr[i]);
}
}
return tempArrayRev.reverse().concat(tempArray);
}
var array = [1,2,3,4,5,6];
document.getElementById('arrayOutput').innerHTML += reverseArray(array,4);
<div id="arrayOutput">Array :<br></div>
This is the answer you can test it.
function reverseArray(n, a) {
var interimArray1 = [];
for (var i = 0; i < a.length; i++) {
interimArray1.push(a[i]);
}
for (var i = num; i >=0; i--) {
interimArray1[i-1] = a[n - i];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
You could use something like this.
function reverseArray(n, arrIn) {
// Splice splits the array in 2 starting at 0 index going n long
var arrOut = arrIn.splice(0,n);
// reverse is pretty straight forward
arrOut = arrOut.reverse();
// Concat joins the two together
return arrOut.concat(arrIn);
}
I am trying to rearrange elements in an array of arrays but have been unsucessful. Can anyone offer suggestions? Here are two options I have tried. I want to swap/switch places for the first and second elements.
arr1 is an array of arrays (i.e. arr[][]) so I created arr2 to be an updated arr1
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
arr2[n][0] = arr1[n][1];
arr2[n][1] = arr1[n][0];
}
The other thing I tried was:
function order(arr[]){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3]];
}
var arr2 = order(arr1);
You also need to create a new array for each item:
var arr2 = [];
for(var n = 0; n < arr1.length; n++) {
arr2[n] = [arr1[n][1], arr1[n][0]];
}
it's quite easy:
var a = arr1[n][0];
arr2[n][0] = arr1[n][1];
arr2[n][1] = a;
you need to save the first value as a variable, because if you do as you did(arr2[n][0] = arr1[n][1];), your two array indexes will have the same value.
You did:
a = 1, b = 2;
a = b;
b = a;
Which resolves in a = 2, b = 2
Also, your code as it is now, doesn't work. You need to create a new array for the simulation of multidimensional arrays in javascript.
for(i = 0; i < (yourdesiredamountofarrays); i++)
{
yourarray[i] = new Array();
}
The first example you need to use a temporary variable for the switch:
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
var tempVal = arr1[n][1];
arr2[n][1] = arr1[n][0];
arr2[n][0] = tempArr;
}
The second example, in JS the variable shouldn't have brackets next to it, as it's just a loosely typed variable name.
function order(arr){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3], arr[n][4]];
}
var arr2 = order(arr1);
Next time, before asking you should check the console. The stackoverflow wiki page on JS has lots of great resources for learning to debug JS.
So i tried to apply bubble sort technique to an associative array.
What i tried is making a normal array and then applying bubble sort.
This worked , so now I'm trying to do the same for my associative array but I can't understand why it doesn't work, can someone explain and tell me how to do this?
Normal Array bubble sort code: <-- This one works
var numbers= new Array()
numbers[0] = 22;
numbers[1] = 3;
numbers[2] = 65;
numbers[3] = 75;
numbers[4] = 500;
numbers[5] = 2;
numbers[6] = 44;
for(var i=0; i<numbers.length; i++)
{
if(numbers[i] < numbers[i+1])
{
var tempGetal = numbers[i];
numbers[i] = numbers[i+1];
numbers[i+1] = tempGetal;
}
}
console.log("Smallest number from array is " + tempGetal);
associative array bubble sort code: <-- Doesn't work
var celsius= new Array()
celsius["Monday"] = 22;
celsius["Tuesday"] = 3;
celsius["Wednesday"] = 65;
celsius["Thursday"] = 75;
celsius["Friday"] = 1;
celsius["Saterday"] = 2;
celsius["Sunday"] = 44;
for(var temp in celsius)
{
if(celsius[temp] < celsius[temp+1])
{
var tempGetal = celsius[temp];
celsius[temp] = celsius[temp+1];
celsius[temp+1] = tempGetal;
}
}
console.log("Smallest number from this array is " + tempGetal[temp]);
Can anyone tell me if the method I'm trying to apply is possible?
Thanks in advance!
There are several reasons why your attempt didn't work, but there is a fundamental flaw in your assumption: the order of properties in an object is undefined, so you should not try to rearrange them.
There's really no reason to use sorting for this. Just go through the object once and find the lowest value:
var min = Infinity;
for(var day in celsius) {
if(celsius[day] < min) {
min = celsius[day];
}
}
console.log(min);
A fancier solution:
var celsius = [];
celsius["Monday"] = 22;
celsius["Tuesday"] = 3;
celsius["Wednesday"] = 65;
celsius["Thursday"] = 75;
celsius["Friday"] = 1;
celsius["Saterday"] = 2;
celsius["Sunday"] = 44;
var min = Object
.keys(celsius)
.map(function(key) {
return celsius[key];
})
.reduce(function(last, next) {
return last < next ? last : next;
}, Infinity);
console.log(min);
Other problems with your approach:
Javascript does not have associative arrays. You should generally not create an array and assign named properties to it (that's what objects are for).
If you iterate through an object with for(var temp in celsius), temp will be the property names, not the temperatures or numerical indices.
With the previous bullet in mind, if temp has the value "Monday", then celsius[temp + 1] = tempGetal will assign tempGetal to the property Monday1.
For the record, your bubble sort doesn't work correctly because you should keep sorting until nothing moves, e.g.
// Sort an array of Numbers
function bubbleSort(arr) {
var oneMoved, // flag if one moved
i, // counter
t; // temp variable
do {
// reset flag
oneMoved = false;
// reset counter
i = arr.length - 1;
while (i--) {
// If array members are out of sequence, swap
if (arr[i] > arr[i+1]) {
t = arr[i];
arr[i] = arr[i+1]
arr[i+1] = t;
// Remember that one moved
oneMoved = true;
}
}
// Keep going as long as one moved
} while (oneMoved)
// Not necessary as array sorted in place, but means function
// can be chained
return arr;
}
// Quick test
var arr = [0, 3, 6, -2, 3];
console.log(bubbleSort(arr)); // [-2, 0, 3, 3, 6]
I am trying to write a function that performs operations on an array and returns a different copy of the array and leaves the original one unchanged. I thought I could do this by declaring var array2 = array and then proceeding with the array operations. What am I doing wrong?
Here is my sample function:
var partition = function(array, p){
var pivot = array[p];
var length = array.length;
// make a copy and move pivot to the front
var array2 = array;
array2[p] = array2[0];
array2[0] = pivot;
// partition the array
var i = 1;
for (var j = 1; j < length; j++){
//console.log('i='+i+', j='+j)
if (array2[j] < pivot) {
var temp = array2[j];
array2[j] = array2[i];
array2[i] = temp;
i++;
}
}
//console.log('array after partitioning: ' + array)
// swap pivot
array2[0] = array2[i-1];
array2[i-1] = pivot;
var answer = {array: array2, p: i-1}
return answer;
};
And my sample call:
var a = [3, 2, 1];
partition(a, 0);
console.log(a); // prints [1,2,3] but I want [3,2,1]
add this line instead of array2=array because it's only create a reference to array not the new array2.
var array2 =array.slice(0); //it will create a new array not the reference.
Fiddle http://jsfiddle.net/N64w3/
var array2 = array.slice(0) or just array.slice() will clone your array
Here you have reference to that