How do I print out the filtered elements from the array?
I tried console.log('randomNumbers/smallNumbers');
But they didn't work.
Please advise, much thanks!
const randomNumbers = [375, 200, 3.14, 7, 13, 852];
const smallNumbers = randomNumbers.filter(num => {
return num < 250;
});
It's not the logging you have troubles with - but Array.filter function. You seem to think it somehow consumes the whole array at once, hence attempt to use length and name the argument the same way as the original array.
What happens instead is that the function you pass in randomNumbers.filter (as its parameter) is called once per each element of that array, taking this element as its first argument.
If result of the function's call for this element is truthy, the element will stay in the result of .filter. If falsy, it gets discarded.
So it can written as simple as this:
const randomNumbers = [375, 200, 3.14, 7, 13, 852];
const smallNumbers = randomNumbers.filter(number => number < 250);
// log the resulting array
console.log(smallNumbers);
// log the small numbers' ratio
console.log((smallNumbers.length / randomNumbers.length).toFixed(2));
const randomNumbers = [375, 200, 3.14, 7, 13, 852];
const smallNumbers = randomNumbers.filter(number => number < 250);
// log the resulting array
console.log(smallNumbers);
// log the small numbers' ratio
console.log((smallNumbers.length / randomNumbers.length).toFixed(2));
Related
Alright, this is a very basic question, but I'm not seeing the fix here. I want to flatten an array that has one layer of depth and at the same time multiply each element by 2. However, when I run flat map on arr1 the console is returning NaN instead of an array of 5 elements with each element being multiplied by 2. Code example below:
const arr1 = [ [2,5] , [5,10,15] ];
const arr2 = arr1.flatMap((el) => el * 2);
console.log(arr2);
Expected // [4, 10, 10, 20, 30]
Actual // [Nan, Nan]
If I run the flatMap without the multiplication I get the array with each element but it's only once I try to mulitply each value that I get the two NaN. What am I missing?
const arr3 = arr1.flatMap((el) => el);
console.log(arr3);
Actaul // [2,5,5,10,15];
The el within your .flatMap() callback represents each of your elements in your array, which in your case will firstly be [2,5] and then on the next iteration will be [5,10,15]. Trying to multiply an array using el*2 will give you back NaN. Instead, what .flatMap() does is if you return an array from the callback, it will take all the elements from within that array and join it into the final resulting array. With this in mind, you can make your callback return an array of mapped/multiplied numbers, which then are all joined together in a final resulting array by .flatMap():
const arr1 = [ [2,5] , [5,10,15] ];
const arr2 = arr1.flatMap(inner => inner.map(el => el* 2));
console.log(arr2); // [4, 10, 10, 20, 30]
const arr1 = [ [2,5] , [5,10,15] ];
var flattened = arr1.reduce(function(a, b) {
return a.concat(b);
});
console.log(flattened)
const arr2 = flattened.flatMap((el) => el * 2);
console.log(arr2)
If you have nested array then you have to first flatten it then apply flatMap.Please read about how flatMap works.
I'm trying to solve a coding challenge
it gives me an array and waits for the answer ,then gives me the next array and so on.
https://www.codewars.com/kata/5648b12ce68d9daa6b000099/train/javascript
I am trying to take this input: var busStops = [[10,0],[3,5],[5,8]] and return 5.
the code is supposed to add the first in each pair to a total while subtracting the second in each pair from the total eg: 10 - 0 + 3 - 5 + 5 - 8 = 5
First my code loops through the inner arrays and outer array ,pushing it into myarr as a regular array eg: [10,0,3,5,5,8].
It then adds the value if it is index is 0 or even and subtracts it if the index is odd.
This actually works!
Until it is given a second array eg: [[3,0],[9,1],[4,10],[12,2],[6,1],[7,10]]
It is still calculating the total correctly but is still remembering the total from the first array meaning it is returning 22 instead of 17
Why?
There is a var answer = 0 that is being executed ahead of the second loop
It should forget the value of the previous answer.
Right?
Edit: I figured out my problem. I just needed to empty myarr after the total was calculated!
let myarr = [];
var number = function (busStops) {
for (var i = 0; i < busStops.length; i++) {
for (var j = 0; j < busStops[i].length; j++) {
/*console.log(busStops[i][j]);*/
myarr.push(busStops[i][j]);
}
}
console.log("test");
var answer = 0;
console.log("test again");
for (let t = 0; t < myarr.length; t++) {
if (t == 0 || t % 2 == 0) {
answer = answer + myarr[t];
} else {
answer = answer - myarr[t];
}
}
console.log(answer);
return answer;
};
The task at your hand tries to somehow find a value (an integer) from an array of arrays (multidimensional array). That task seems to be reducing that multidimensional array into a single integer.
Luckily, JavaScript has some powerful array methods and one of them is the reduce method:
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. Source: MDN
The reduce method tries to reduce an array's elements into a single value and in your case we want to reduce that multidimensional array into a single value that is the number persons who are still in the bus.
Before typing some code, let's dig a bit deeper into the reduce method:
It accepts 2 parameters, a callback function that acts as the reducer and the initial value to be used in the first iteration of the reduce method.
The reducer callback function, on its own, accepts 4 parameters that are supplied by the reduce method. You may learn more about those parameters here as am only going to focus on the first 2 parameters the reducer accepts:
previousValue: hold the value from the previous reducer call. On first call, it contains the value you set to the initial value parameter of the reduce method or, if you didn't supply an initial value, previousValue shall hold the value of your array's first element (arr[0]).
currentValue: hold the current reduce iteration's item.
Now, let's get back to the task we have, we need to calculate the number of persons who are still in the bus based on a supplied multidimensional array. Each item in that multidimensional array is an array of two values where the result we need at the end is: the sum of the differences between each array, in the multidimensional array, first and second values (sum = multiDim[i][0] - multiDim[i][1] + multiDim[i + 1][0] + multiDim[i + 1][1] etc...).
To solve this task, we'll reduce that multidimensional array into a single number (let's call it result) by using a simple reducer function that will start by an initial value of 0 (as we're calculating a sum in our case) and will add, to the result, the difference between the first and the second values of the array supplied by the reduce at each iteration.
To illustrate, here's a live demo:
/**
* a function that calculates and returns the number of person who are still in the bus or precisely, the sum of the differences between "c[0]" and "c[1]"
* busArray: the supplied multidimensional array to reduce
* the reducer accepts two parameters:
* r: the result from the last call to the reducer function (initially set to 0, the initial value (see second parameter passed to the "reduce" method))
c: hold the current iteration's array.
*/
const calculateWhoAreInTheBus = busArray => busArray.reduce((r, c) => r += c[0] - c[1], 0);
/** test the created "calculateWhoAreInTheBus" function */
console.log(calculateWhoAreInTheBus([
[10, 0],
[3, 5],
[5, 8]
])); // should print: 5
console.log(calculateWhoAreInTheBus([
[3, 0],
[9, 1],
[4, 10],
[12, 2],
[6, 1],
[7, 10]
])); // should print: 17
console.log(calculateWhoAreInTheBus([
[3, 0],
[9, 1],
[4, 8],
[12, 2],
[6, 1],
[7, 8]
])); // should print: 21
console.log(calculateWhoAreInTheBus([
[0, 0],
[0, 0]
])); // should print: 0
I would advice you to use Array.prototype.reduce instead. For example like this:
const reducer = (previous, current) => previous + current[0] - current[1];
const answer = busStops.reduce(reducer, 0);
It is very brief (although this is not a goal in and of itself) and the reducer function does almost trivial work, so it does not complicate unneccesarily. Best of all it encapsulates the functionality with a minimal need of extra variables.
Othwerwise you could simplify your function a bit but use the let keyword to keep variables locked to scope like:
function number(busStops) {
let answer = 0;
for (let bs of busStops) {
answer += bs[0] - bs[1];
}
return answer;
}
Looking for general advice on approaches here. Description and pseudocode below:
Array1 has 100 objects type integer
Array2 has 100 objects type integer
Create Array 3 10,000 objects summing the two arrays
Array3.1 = Array1.[Field1] from 1 to 100 + Array2.1.[Field1]
Array3.2 = Array1.[Field1] from 1 to 100 + Array2.2.[Field1]
Array3.3 = Array1.[Field1] from 1 to 100 + Array2.3.[Field1]
……
Array3.100 = Array1.[Field1] from 1 to 100 + Array2.100.[Field1]
Challenges:
Not sure how to easily reference the field within an object in the array. I can pull up the object line but this returns the entire object whereas I only want to pull one field. This would be helpful beyond this particular question.
Not sure about the best method to create the new array, whether it should be a loop or something else.
Further background
The final objective will be to create an output that compares the sum of the specific field for every pair within the two arrays to find and then rank them from best to worst.
It's not that difficult.
Every entry in the resulting array is just the 2nd array with the value at the current index of the first array added to it.
const a1 = [0, 5, 10, 15, 20];
const a2 = [0, 2, 4, 6, 8];
const result = a1.map(x => a2.map(y => x + y));
console.log(result);
If you don't want the resulting array to nested, use flatMap:
const a1 = [0, 5, 10, 15, 20];
const a2 = [0, 2, 4, 6, 8];
const result = a1.flatMap(x => a2.map(y => x + y));
console.log(result);
Given two array of same length, return an array containing the mathematical difference of each element between two arrays.
Example:
a = [3, 4, 7]
b = [3, 9, 10 ]
results: c = [(3-3), (9-4), (10,7)] so that c = [0, 5 3]
let difference = []
function calculateDifferenceArray(data_one, data_two){
let i = 0
for (i in data_duplicates) {
difference.push(data_two[i]-data_one[i])
}
console.log(difference)
return difference
}
calculateDifferenceArray((b, a))
It does work.
I am wondering if there is a more elegant way to achieve the same
Use map as following:
const a = [3, 4, 7]
const b = [3, 9, 10]
const c = b.map((e, i) => e - a[i])
// [0, 5, 3]
for-in isn't a good tool for looping through arrays (more in my answer here).
"More elegant" is subjective, but it can be more concise and, to my eyes, clear if you use map:
function calculateDifferenceArray(data_one, data_two){
return data_one.map((v1, index) => data_two[index] - v1)
}
calculateDifferenceArray(b, a) // < Note just one set of () here
Live Example:
const a = [3, 4, 7];
const b = [3, 9, 10 ];
function calculateDifferenceArray(data_one, data_two){
return data_one.map((v1, index) => v1 - data_two[index]);
}
console.log(calculateDifferenceArray(b, a));
or if you prefer it slightly more verbose for debugging et. al.:
function calculateDifferenceArray(data_one, data_two){
return data_one.map((v1, index) => {
const v2 = data_two[index]
return v1 - v2
})
}
calculateDifferenceArray(b, a)
A couple of notes on the version of this in the question:
It seems to loop over something (data_duplicates?) unrelated to the two arrays passed into the method.
It pushes to an array declared outside the function. That means if you call the function twice, it'll push the second set of values into the array but leave the first set of values there. That declaration and initialization should be inside the function, not outside it.
You had two sets of () in the calculateDifferenceArray call. That meant you only passed one argument to the function, because the inner () wrapped an expression with the comma operator, which takes its second operand as its result.
You had the order of the subtraction operation backward.
You could use higher order array method map. It would work something like this:
let a = [2,3,4];
let b = [3,5,7];
let difference = a.map((n,i)=>n-b[i]);
console.log(difference);
you can read more about map here
trying to write a function that takes the change you have in an array [quarters,dimes,nickels,pennies] and second parameter of the cost value n.
So ([quarters,dimes,nickels,pennies],n)
then I wanna use the reduce method to create an ES6 style of code
I want to understand how to use reduce and grab the second parameter in my code
const changeEnough = ([25, 20, 5, 0], 4.25)
const ct = (accumulator, currentValue) =>
((accumulator + currentValue) - intialValue >= 0);
console.log(changeEnough.reduce(ct));
error message I am getting is
changeEnough.reduce is not a function
I have figured that I am not asking the other value of 4.25 in my code
Your declaration of changeEnough is wrong. Using the comma operator like that results in the final value - what actually is it? 4.25:
const changeEnough = ([25, 20, 5, 0], 4.25);
console.log(changeEnough);
So pass the second value as a second argument to reduce. You can make this simple by using an array for changeEnough:
const changeEnough = [[25, 20, 5, 0], 4.25];
const ct = (accumulator, currentValue) => ((accumulator + currentValue) - intialValue >= 0);
console.log(changeEnough[0].reduce(ct, changeEnough[1]));
(Also make sure you've defined initialValue.)