I am trying to return the largest element in a list page:
page = [1,2,3];
R.max(page); // returns a function.
R.max(-Infinity, page); // seems correct but doesn't work as expected.
I don't have the ramda package installed, so this is untested, but from the documentation max() only takes two arguments, so you would have to reduce() your array upon it:
var page = [1, 2, 3],
result = R.reduce(R.max, -Infinity, page);
// 'result' should be 3.
Use the apply function: https://ramdajs.com/0.22.1/docs/#apply
const page = [1, 2, 3];
R.apply(Math.max, page); //=> 3
Related
I've got 50 different lists, called list1, list2, and so forth. I also have a function which rolls a random number between 1 and 50 and then stores the value in a variable called randomNumber, and what I want to do is to access the list with a matching number.
My attempt at access the list looked like this:
document.getElementById("demo").innerHTML = list + randomNumber;
One solution would be to put all 50 lists into one list, and then use the randomNumber to access the right list through index. I am however still curious if this can be done in a way similar to what I was decribing above the code though.
Inserting the arrays into another array and accessing them by their indexes (or assigning them to property values on an object and accessing them by their associated property names) is the right approach.
The only way to reference scoped variables by strings representing their names is by using eval().
However, I will echo the linked MDN article: Don't do this.
⚠️ Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!, below.
Here's an example of using eval to reference each of the arrays below:
const list1 = [1, 2, 3];
const list2 = [4, 5, 6];
console.log(eval('list' + '1')); // [1, 2, 3]
console.log(eval('list' + '2')); // [4, 5, 6]
And here's an example of the recommended approach:
const list1 = [1, 2, 3];
const list2 = [4, 5, 6];
// As an object:
const listNames = {
list1,
list2,
};
// As an array:
const lists = [
list1,
list2,
];
console.log(listNames['list' + '1']); // [1, 2, 3]
console.log(lists[0]); // [1, 2, 3]
console.log(listNames['list' + '2']); // [4, 5, 6]
console.log(lists[1]); // [4, 5, 6]
I saw this function , though it works fine but I am bit puzzled about the function expressions. Here is the code
mapForEach(arr, fn) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(fn(arr[i]))
}
return newArr;
}
can anybody explain to nme what this rather complicated code is actually doing?
Lets say you have var array = [1, 2, 3, 5]; and then run var array2 = mapForEach(array, function(i) { return i * 2; })
array2 would then contain [2, 4, 6, 10].
So it returns a new array where you have the ability to modify each record with a function
mapForEach enumerates an array and calls a supplied function on each element.
example:
var a = [1, 2, 3];
console.log(mapForEach(a, (x) => x * 2));
would create a new array with the values (and output to console):
[2, 4, 6]
Basically it is an implementation of javascript native array function map, which creates a new array with the results of calling a provided function on every element in this array.
More info about mentioned function you can find here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
As I'm learning the forEach() method in JavaScript, I have several questions related to it.
Currently I've written the following piece of code:
var arr = [1,2,3,4,5,6];
arr.forEach(function(elem, idx, arr){
elem=elem*2;
});
alert(arr); // "1,2,3,4,5,6"
My goal is to simply multiply each element in arr by 2, however when I use alert to examine the final values it seems that values inside arr hasn't been modified. What's the problem here?
Also I'm a little confused about the 3 arguments that forEach's function takes. First, is it required to pass in 3 arguments? What will happen if one doesn't provide exactly 3 arguments? Some tutorials I've looked at seem to provide only 1 argument, yet the explanation wasn't clear. Second, do the names of arguments matter (e.g. e, elem, or element)?
Thank you.
Your approach
You are not assigning new value to anything else but the elem, which is only in callback's scope. Modify your code, so that the elem * 2 is assigned to arr[idx]. Working example:
var arr = [1, 2, 3, 4, 5, 6];
arr.forEach(function(elem, idx) {
arr[idx] = elem * 2;
});
document.body.textContent = arr;
Better approach
For tasks like that however, you should use map:
var arr = [1, 2, 3, 4, 5, 6];
arr = arr.map(function(num) {
return num * 2;
});
document.body.textContent = arr;
The array is not getting modified cus you are not modifying it. To do that update the code as following.
var arr = [1,2,3,4,5,6];
arr.forEach(function(elem, idx, arr){
arr[idx] = elem*2
});
console.log(arr);
If you check the console you would see the updated arr.
you cannot edit the array in place by returning the new value or changing elem. You can however use the idx variable like arr[idx] = elem * 3 or use the map function.
you can omit the parameters that you don't need
you can name them whatever you want
For first problem, just use map
var arr = [1,2,3,4,5,6];
arr = arr.map(function(elem){
return elem*2;
});
alert(arr); // "2,4,6,8,10,12"
arguments is optional, and names doesn't matter at all.
The arguments are optional.
idx lets you know the index of the array element you are currently evaluating.
arr, is the array you are evaluating.
so elem == arr[idx]
For the life of me, I just can't figure out what I'm doing wrong here.
I'm trying to use both the reduce and concat array methods to take all of the values of a 2d array and combine them into a single value (basically condense them into a single array and then sum them up).
The problem that I keep running into is that when I try to make a for/loop to concat each array element, the argument that I'm passing into the function is not being recognized as an array, thus my call to .concat() is failing. I've placed a console.log() at the beginning of the function to see if the element is being recognized as the first array element in the 2d array, and it's coming up as "1"(?).
I tried another test outside of the function, and it logs as the actual array element. What am I doing wrong here? code below:
var arrays = [[1, 2, 3], [4, 5], [6]];
var myArray = arrays[0]; // Test
console.log(myArray); // Test
var flatArray = arrays.reduce(function(arrays)
{
console.log(arrays[0]); // Test
for (var i = 0; i < arrays.length - 1; i++)
{
arrays[0].concat(arrays[i+1]);
}
return arrays;
});
console.log(flatArray);
This is the output that I keep getting:
Array [ 1, 2, 3 ]
1
TypeError: arrays[0].concat is not a function
It's almost seems like array is being converted to a number-type when inside the function...?
You have an error in your code here:
var flatArray = arrays.reduce(function(param) {})
that param will be an element of your arrays vector.
Check this https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You are using .reduce() incorrectly and you don't even need to use it to flatten an array. You can just do this:
var flatArray = [].concat.apply([],arrays);
Working demo: http://jsfiddle.net/jfriend00/wfjyfp42/
To understand .reduce(), the callback you pass it gets four arguments (see MDN reference). The first two arguments are important in using .reduce() correctly:
callback(previousValue, currentValue, index, array)
The previousValue is the accumulated value so far in the reduction. The currentValue is the next element of the array that is being iterated. The last two arguments do not need to be used if not needed.
Your code is only using the previousValue so it is never looking at the next item in the array as passed in by .reduce().
You could make a solution work using .reduce() like this:
var flatArray = arrays.reduce(function(previousValue, currentValue) {
return previousValue.concat(currentValue);
}, []);
Working demo: http://jsfiddle.net/jfriend00/2doohfc5/
Reduce performs an operation on two elements.
var sum = [[1, 2, 3], [4, 5], [6]].reduce(function(a, b) {
return a.concat(b);
}).reduce(function(a, b) {
return a + b;
});
Just look at the code and you'll understand what I mean:
var aBackup = [3, 4]; // backup array
var a = aBackup; // array to work with is set to backup array
a[0]--; // working with array..
a = aBackup; // array o work with will be rested
console.log(a); // returns [2, 4] but should return [3, 4]
console.log(aBackup); // returns [2, 4] too but should return [3, 4] too
You need to make real copies of your Arrays instead of just using a reference:
var aBackup = [3, 4]; // backup array
var a = aBackup.slice(0); // "clones" the current state of aBackup into a
a[0]--; // working with array..
a = aBackup.slice(0); // "clones" the current state of aBackup into a
console.log(a); // returns [3, 4]
console.log(aBackup); // returns [3, 4]
See MDN for documentation on the slice-method
Doesn't javascript uses pointer for arrays ? Should var a = aBackup; do a copy ? otherwise the results seems normal to me...
An array is a reference type of object, so changes made to it will change the underlying value it points to, a and aBackup will point to the same value, and a change made to a will change aBackup aswell.
It is because when you do this, you are not making a copy of the array, but infact a reference to the original array.
var a IS aBackup; // if you will
When you need to do is clone the backup array.