I have a CSV file of some data and for each line, I split it by the comma to get an array vals.
Now I want to pass vals into a function, but "flatten" it (without changing the function because it is used elsewhere)
function foo(x, y, z) {
return x*y*z:
}
var vals = [1, 3, 4];
//want a shortcut to this (this would be a nightmare with like 20 values)
foo(vals[0], vals[1], vals[2]);
Edit:
Sorry, kind of left out a big detail. I only want part of the array, like the first 10 elements of a 12 element array. Any shortcut for this?
Use Spread operator; if you are using es6.
var vals = [1,2,34,5]
foo(...vals)
Or you could also use apply
function foo(a,b,c,d,e) {
console.log(a,b,c,d,e)
}
var vals = [1,2,3,4,5]
foo.apply(null, vals)
first you don't need var in the parameters,
second, you may use the spread operator
function foo(x, y, z) {
return x * y * z;
}
var vals = [1, 3, 4];
console.log(foo(...vals));
reference: spread operator
Related
I need your help since i'm stuck at the challenge from checkio.
What am i missing? I get back:
Your result:"one,two,three"
Right result:"one,three,two"
The Challenge:
You are given two string with words separated by commas. Try to find what is common between these strings. The words are not repeated in the same string.
Your function should find all of the words that appear in both strings. The result must be represented as a string of words separated by commas in alphabetic order.
UPDATE
this is my code:
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
match.toString() doesn't change the value of match variable. You need to return it from the function.
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
Explanation
There are two kinds of methods.
Mutator Methods
The first kind changes the original variable. You don't need to reassign the variable in case of those methods. Some of them are reverse(), fill(), etc
Note: These methods are only for reference type(objects, array) not for value types(string, number, boolean).
const arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); //[4, 3, 2, 1]
Accessor Methods
The second type are those methods which doesn't change the original variables but it returns are new value which is used by assigning it to a variable using =.
Some of them are map(), filter() etc.
let arr = [1, 2, 3, 4];
arr.map(x => x * x); //This line has no impact at all
console.log(arr) //Nothing is changed
arr = arr.map(x => x * x); //This line changes 'arr'
console.log(arr); //[1, 4, 9, 16]
Now toString() is of second type(accessor method) type. Just calling that method never changes the original variable. You need to reassign or return according to your needs
Is it possible to use lodash to iterate over a collection and pass the item to a function that requires two (or more) arguments? In the following example, the function should take two values and add them. The map should take an array and add 10 to each. The following is how I thought this worked:
function x (a, b) {
return a + b
}
var nums = [1, 2, 3]
console.log(_.map(nums,x(10)))
--->ans should be [11, 12, 13]
--->actually is [ undefined, undefined, undefined ]
What you're essentially trying to do here is "curry" the x function, which lodash supports via curry(). A curried function is one that can take its arguments one at a time: if you don't provide a full set of arguments, it returns a function expecting the remaining arguments.
This is what currying looks like:
function x(a,b) {
return a + b;
}
x = _.curry(x); //returns a curried version of x
x(3,5); //returns 8, same as the un-curried version
add10 = x(10);
add10(3); //returns 13
So your original code is very close to the curried version:
console.log(_.map([1,2,3], _.curry(x)(10))); //Prints [11,12,13]
(As was pointed out in the comment on the question; Function.prototype.bind can also be used for currying, but if you're already using lodash, you might as well use something specific to the task)
You can do it like this:
var numbers = [1, 2, 3];
function x(value, number) {
return value + number;
}
console.log(_.map(numbers, function(value) { return x(value, 10) }));
Sure, closure is awesome! Just make a function that "closes" (wraps) your x function and passes 10 as its second argument.
function x (a, b) {
return a + b;
}
function addTen (number) {
return x(numberToAddTo, 10);
}
var nums = [1, 2, 3];
console.log(_.map(nums, addTen));
I just signed up in codewars and I'm trying the first kata. This is the question:
Write a function to multiply a number (x) by a given number (y) a certain number of times (n). The results are to be returned in an array.
eg.
multiplyBy(2, 4, 6);
The output is: [8, 32, 128, 512, 2048, 8192]
I believe my code is write, when I do console.log I get the array that the exercise is asking for, but it won't let me proceed. I'd appreciate some help, thanks!
var array = [];
function multiplyBy(x, y, n) {
while (x<2049){
var z = x*y*n;
var x = z;
array.push(z)
}
}
multiplyBy(2,2,2);
console.log(array);
return array;
You have a few things going on outside your function which make it only work one time. Make sure that you keep everything inside the function until the last return
function multiplyBy(x, y, n) {
var array = []; // var this inside your function
for (; n > 0; --n) { // the loop is only supposed to happen n times
x = x * y; // you can reuse this variable (x)
array.push(x);
}
return array; // return statement should be inside your function
}
// example of logging the returned value
console.log(multiplyBy(2, 4, 6)); // [8, 32, 128, 512, 2048, 8192]
Your while loop also was hardcoded to x<2049, but this isn't always the case as it depends on the n parameter given to the function
it won't let me proceed
There are 3 issues in the code you posted that probably prevent you from proceeding,
The return array is probably throwing a syntax error because it's outside a function
In your code, calling multiplyBy several times appends the new values onto the end of the previous array
They are probably testing your function against other sets of values to check it works as expected, which is not true in your function, i.e. you gave the example inputs of 2, 4, 6 but used 2, 2, 2 in your own code
As a final note, try to get into the habbit of indenting your code, it'll save you headaches reading it later as it lets you quickly see where blocks begin and end
Your return is outside the function. And all calls to multiplyBy populate the same array. And your logic is flawed.
Probably, it should be
function multiplyBy(x, y, n) {
var array = [];
while (n--) array.push(x *= y)
return array;
}
console.log(multiplyBy(2,4,6));
Or, in ECMAScript 6,
var multiplyBy = (x, y, n) => Array(n).fill().map(a => x*=y);
ramove the return at the end, this must be used in function to return something, if not used the function will return undefined.
Look at this (single-line solution):
function multiplyBy(x,y,n) {
return Array.apply(null, new Array(n)).map(function(v, i) { return x * Math.pow(y, i + 1); });
}
DEMO
I am using the eval() function to create an calculator, and as you know eval returns a string (I am referring to this tutorial), for example 20+30. What I want now is to split this string so I will have an array of data like [20,30,50] where the 20 and 30 are the operands and 50 is the result in this case.
What I did so far is:
var input = document.getElementById('screen');
var result= '20+30'; // as an example
var firstOperand = result.split('+', 1); //this is taking the first operand
What I really want is as I mentioned to turn my input value that is string "20+30" to an array: myArr = [20,30,50].
Any help?
Use the power of maps and reduce!
result = '1+2+3+4+5+6+7+8+9';
a = result.split('+').map(function(x){ return parseInt(x) });
b = a;
b.push(a.reduce(function(p, c) { return p+c; }));
// b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 45]
Btw you shouldn't use eval(), look into the Shunting-yard algorithm instead. Code examples for the algorithm can be found here at SO and at Rosettacode.
you can create the array passing to the split function only the separator.
var myArr = result.split('+');
now you need to add the result:
myArr.push("50");
From the following thread (Multiplying an array with a single value by a number?) I got the information that it is not possible to multiply a number to all elements within an array by executing [1, 2]*3. But since I have to do this I was wondering if there is an smart way of doing this?
I know I could write a function which iterates through all elements and multiply a number to each element manually. But I was wondering if there is a smarter way out there?
Maybe there are some libraries out there which implements some math functions where I can multiply a number to all elements of an array?
Or do you think the map function of Array can be used for this purpose?
You can indeed use the map function:
function multiply(input) {
return input * 3;
}
var myArray = [1, 2];
var myNewArray = myArray.map(multiply);
What this does is perform a function you provide on each element in the array, and return a new array with the results.
If you're already using jQuery, you can make it a little more concise with the each function:
$.each(myArray, function(index, value) {
myArray[index] = value * 3;
});
This changes the existing array. Although, using the plain-JS approach, you could do myArray = myArray.map(multiply); if you don't want a new variable.
I made a jsFiddle as an example.
This is easy with a library like math.js, which comes with matrix support. You could do something like:
var result = math.multiply([1, 2], 3);
or using the expression parser:
var result = math.eval('[1, 2] * 3');
Similar to Jos de Jong's answer, if you are using numericjs you can do
var result = numeric.mul([1, 2], 3);
To give the result [3, 6].
You have not defined your array as an array variable: Just do as following:
function times2(theArray){
var newArray = [];
for (i = 0; i < theArray.length; i++) {
newArray.push(theArray[i] * 2);
}
return newArray;
}
document.write("Array double = ",times2([1,2,3,4,5]).toString() , "<br>");
Now it does not matter how many elements you have in your array, it multiplies them by 2. You can choose any number instead of 2.