Can someone explain me a line of code in a function - javascript

Could someone please explain me what does this line of code actually means step by step.
arrRes.push(fn(arr[i]));
I understand the push part but I am struggling to grasp the code in the parenthesis.
The whole function looks like this :
function arrayCalc (arr, fn) {
arrRes = [];
for (let i = 0; i < arr.length; i++) {
arrRes.push(fn(arr[i])); // <--- this line here in the parenthesis
}
return arrRes;
};
Sorry if this is a dumb question but I've watched the tutorial video for five times and I just can't understand what that line exactly means.
Thanks!

there is some function fn passed as argument and array arr
arrRes.push(fn(arr[i])); - means:
take value from arr (index is i)
execute function fn with value as a parameter
whatever is result, push it to arrRes
example
function arrayCalc (arr, fn) {
arrRes = [];
for (let i = 0; i < arr.length; i++) {
arrRes.push(fn(arr[i]));
}
return arrRes;
};
const someArr = [1,2,3];
function someFunction(number) {
return number * 10;
}
function someOtherFunction(number) {
return `${number}_Z`;
}
console.log(arrayCalc(someArr, someFunction)) // [10, 20, 30]
console.log(arrayCalc(someArr, someOtherFunction)) // ['1_Z', '2_Z', '3_Z']

This is usually called a mapping: apply a function to each element of a collection... Thus if you have an array [1,2,3] and map it with a function that multiplies a number by 2, you will end with an array equals to [2,4,6].
To compute it, you need an array, arr and a function fn. Then for each element of arr in turn you apply fn to it and place the result at the end of the new collection. You can write it as:
arrRes = [];
for (let i = 0; i < arr.length; i++) {
var dummy = arr[i];
var mapped = fn(dummy);
arrRes.push(mapped);
}

Related

duplicate elements of an array in JavaScript

How to duplicate elements of an array in JavaScript and add them to the same array.
function duplicate(arr) {
// Write Logic here
var position,lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr[position] = arr[i];
position++;
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Please explain why the above code is not working. I'm getting "Incorrect Output" as error.
Also, I've come up with another way as shown below. But I'd like to know what's wrong with this approach.
function duplicate(arr) {
// Write Logic here
var lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr.push(arr[i]);
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Thank you
An alternative approach would be to use push to add elements to the end of the array. That way you don't need that extra position variable.
function duplicate(arr) {
const len = arr.length;
for (let i = 0; i < len; ++i) {
arr.push(arr[i]);
}
return arr;
}
let arr= [1, 2];
console.log(duplicate(arr));
You can achieve this by using Spread syntax (...)
Try this :
function clone(arr) {
arr.push(...arr);
return arr;
}
var arr=[1,2];
console.log(clone(arr));

Create array with function javascript

I need to create function that creates and returns array. Its size needs to match the rows parameter, and each next element contains consecutive integers starting at 1. To call this function I need to use argument 5. Here below is what I wrote so far. Can you tell me what's wrong here?
function createArray(rows) {
for(let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}return rows;
}
createArray(5);
You need to create an array and return it, whereas you return just rows which is a number. The idea of using a for loop is the best way to go. In that loop you just need to set the values in the array accordinlgy.
Another problem in your code is that rows is of type number and does have a property length but that does not have the desired value. So we just use rows in the for loop. We start the loop with i = 0 because array indices start at 0.
Code
function createArray(rows) {
let arr = new Array(rows);
for (let i = 0; i < rows; i++) {
arr[i] = i + 1;
}
return arr;
}
console.log(createArray(5));
We can not use length property for number. create an empty array and then push values into that array until required size is achieved.
function createArray(rows) {
var arr = [];
for(let i = 1; i <= rows; i++) {
arr.push(i);
}return arr;
}
createArray(5);
I think what you want is createArray(5) return [1,2,3,4,5] if that's the case you could do this
function createArray(rows) {
const arr = []
for(let i = 1; i <= rows; i++) {
arr.push(i);
}
return arr;
}
console.log(createArray(5));
The problem is, that rows.length is not available on 5, because 5 is a number.
You have to use an array as parameter:
Array(5) creates an array with the length of 5 and fill("hello") fills this array with "hello" values.
function createArray(rows) {
for (let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}
return rows;
}
const rows = Array(5).fill("hello");
createArray(rows);
I don't know, if this is the behaviour you want, if not, I misunderstood your question.

why I am getting undefined result with for loop function?

why this code return undefined
I can't spot the reason
function findShort(s){
let splitted = s.split(' ');
let result = splitted[0].length ;
let looped
for (var i=0 ; i++ ; i<splitted.length){
looped = splitted[i].length;
if (looped < result) {return looped}else {return result }}
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
I am supposed to get numbers of smallest word
Your for loop condition and increment are inverted:
for (var i=0 ; i++ ; i<splitted.length){ ...
should instead be:
for (var i = 0; i < splitted.length; i++) { ...
You also have to fix your looping code as it returns in both branches of you inner if statement, which means only a single iteration will run.
If you want to return the length of the smallest word, do this:
function findShort(s) {
let splitted = s.split(' ');
let result = splitted[0].length;
for (let i = 0; i < splitted.length; i++) {
const looped = splitted[i].length;
if (looped < result) {
result = looped;
}
}
return result;
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));
Or shorter using Array.prototype.reduce():
function findShortest(s) {
return s.split(/\s+/).reduce((out, x) => x.length < out ? x.length : out, s.length);
};
console.log(findShortest('bitcoin take over the world maybe who knows perhaps'));
Your for-loop implementation is wrong, it is supposed to be:
for (var i=0; i<splitted.length; i++)
Order of condition and increment is wrong in you for loop as well as the code inside the loop,
it will check for the first element only as you have a return in all conditions.
Here's the correct one
function findShort(s) {
let splitted = s.split(' ');
let result = splitted[0].length;
let looped
for (var i = 0; i < splitted.length; i++) {
looped = splitted[i].length;
if (looped < result) { result = looped }
}
return result;
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));

forEach does not mutate an array that I pass in

I've created a simple forEach function and I'm trying to understand why, when I run it with myArray, it doesn't mutate the array even though I run element*2.
function forEach(array, callback) {
for (var i = 0; i < array.length; i++) {
callback(array[i],i,array)
};
}
var myArray = [1,2,3]
forEach(myArray,function(element){element*2})
console.log(myArray)///[1,2,3]
You have to modify the array in the for loop, like this:
function forEach(array, callback) {
for (var i = 0; i < array.length; i++) {
array[i] = callback(array[i],i,array)
};
}
var myArray = [1,2,3]
forEach(myArray,function(element){return element*2})
console.log(myArray)
As we were discussing in the comments, the best way would be to implement something like the map function: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
function map(array, callback) {
var out = [];
for (var i = 0; i < array.length; i++) {
out.push(callback(array[i],i,array))
};
return out;
}
var myArray = [1,2,3]
var myOtherArray = map(myArray,function(element){return element*2})
console.log(myArray)
console.log(myOtherArray)
This way myArray is not touched, you create a new one. This is usually the best option, but sometimes you may want to modify it in place, because it is huge or for some other (good?) reason. In that case you can use the first option.
You should assign new array element value, because primitive types (like numbers in your case) are immutable, so element * 2 does not modify element.
To do the job, you should not touch you current forEach implementation, because forEach is not supposed to return values from callback (this is not map). In this case you should do something like this:
function forEach(array, callback) {
for (var i = 0; i < array.length; i++) {
callback(array[i], i, array);
}
}
var myArray = [1,2,3];
forEach(myArray, function(element, i, arr) {
arr[i] = element * 2;
});
document.write(JSON.stringify( myArray ));
This should work, explicitly assigning the variable.
function forEach(array, callback) {
for (var i = 0; i < array.length; i++) {
array[i] = callback(array[i])
};
}
var myArray = [1,2,3]
forEach(myArray,function(element){return element*2})
console.log(myArray)///[1,2,3]
Yep, bad answer. This [snippet] would do it though.
Anyway, in modern browsers we have Array.forEach to availability
function foreach(array, callback) {
for (var i = 0; i < array.length; i++) {
array[i] = callback(array[i]);
// ^ assign the new value (from the callback function)
};
}
var myArray = [1,2,3]
foreach( myArray, function (element){ return element * 2 } );
// ^ return the new value
document.querySelector('#result').textContent = myArray;
<pre id="result"></pre>

Define a function that contains an unknown function in javascript

i was asked to define a function reduce, that has three parameters, an array, an unknown function, and a number, and reduces the array into a number
and this is was i was given before i was asked to define the function
reduce([1, 2, 3], function(total, number) {
return total + number;
}, 0); // should return 6
I am a bit clueless on what this is asking me to do to be completely honest
if i could at least get some guideline id be grateful
here is my attempt
var reduce = function(array, func, initial){
function func(){
}
for( var i = 0; i < array.length; i++){
func(initial, array[i]);
}
}
Try:
function reduce(list, f, acc) {
return list.length ?
reduce(list.slice(1), f, f(acc, list[0])) :
acc;
}
Simple.
You need to be sure to create a total variable which will be redefined after every function call. You were very close. Try this out:
var reduce = function(array, func, initial){
var total = initial,
arr_len = array.length;
for(var i = 0; i < arr_len; i++){
total = func(total, array[i]);
}
};

Categories

Resources