How to use the reduce operation in javascript? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I am currently trying to simplify the following code written in Javascript
let x = 5;
let y = 10;
let z = 19;
let answer;
arrays = ["x", "y", "z"];
if("x" in arrays){
answer = x;
}
if("x" in arrays && "y" in arrays){
answer = x + y
}
The code will continue on and on for all the possible combinations of x, y and z. What I want to know is how I can simplify the above block of code and achieve the same result.
Thank you.

Instead of individual variables, create an object with your name/value pairs. Then it's trivial to iterate over the names in the array, use them to access the values in the object, and add them together. In fact, this is most naturally expressed as a reduce operation:
let vals = {
x: 5,
y: 10,
z: 19
};
let answer = ["x", "y", "z"].reduce((a, k) => a + vals[k], 0);
console.log(answer);

Related

create an array of objects from objects javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have this objects from google API, if I console.log(ret) I have this:
{name:x, stars:5},
{name:y, stars:4},
{name:j, stars: 3}
I am getting this result from the following loop:
for (let i = 0; i < fromGoogle.length; i++) {
let ret = fromGoogle[i];
}
I want to create an Array of Objects like:
[{...},{...},{...}]
How do I do it?
Thank you, I am new at JS
If you have, for instance, objects referenced by individual variables:
let a = {name:x, stars:5};
let b = {name:y, stars:4};
let c = {name:j, stars: 3};
you can create an array of them using an array initializer (aka "array literal"):
let array = [a, b, c];
You don't need the individual variables, though, you can do this:
let array = [
{name:x, stars:5},
{name:y, stars:4},
{name:j, stars: 3}
];

How can I reverse an array using map? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I get the error that "array" is undefined when running this code. In my solution, I need to use map() to reverse my array.
var names = ["Lars", "Jan", "Peter","Bo", "Frederik","Anna"];
var newArray = array.slice(0).reverse().map(function(name){
return name;
});
console.log(backwards(newArray));
you have to provide the array names instead of using array, which is undefined
var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"]
var newArray = names.slice(0).reverse().map(function(name) {
return name;
});
console.log(newArray)
also most of the functions do nothing in this case. You really only need names.reverse() as mentioned in the comment.
If you do want to use map(), it's a bit more complicated, and not the right function to use for reversal.
update
How can I convert it to a function???
well reverse already is a function, but if you want to use map and create a new function using es6 style convention, (const foo = () => {})) you could use map as an iterater, as Nina Scholz did in her answer.
var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"]
const backwards = (arr) => arr.map((_, i) => arr[arr.length - i - 1]);
console.log(backwards(names))
console.log(backwards([0, 1, 2]))
You could map the items with a calculated index.
var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"],
reversed = names.map((_, i, a) => a[a.length - i - 1]);
console.log(reversed);
Hmm there is no point in using map it can be simply done on this way
var newArray = names.reverse();

Find out which of four variables contains the largest integer in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have four variables, a, b, c, and d, which each contain a number between 0 and 100, and I don't know the code to determine which one of the four variable contains the largest number.
I need to know the name of the variable that holds the highest value, not the highest value itself!
let a=8, b=1, c=9, d=3
let obj={a,b,c,d},
greatest=Object.values(obj).sort().pop()
key = Object.keys(obj).find( k => obj[k] === greatest )
console.log(key) // Logs "c"
Check out this, worked for me...
Math.max(a, b, c, d);
You can use this code. This also works for the negative integers, in case you have negative values in future. It will be useful for you.
var a=10, b=20, c=15, d = 5;
var array = [a, b, c, d];
var largest=a;
for (i=1; i<=array.length;i++){
if (array[i]>largest) {
largest=array[i];
}
}
console.log(largest);
You can use recursive calls.
Store all the variables in an array. Initial call is by doing findMax(a, a.length-1).
function findMax(a, index) {
if (index > 0) {
return Math.max(a[index], findMax(a, index - 1));
} else {
return a[0];
}
}
var x = findMax([1, 4, 50, 3], 3);
console.log(x);
//In inital call pass array.length -1
Sort the array in descending order and get the first one.
[a, b, c, d].sort(function(num1, num2){return num2-num1;})[0]

how to add array values in javascript using push [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have declared an array in JavaScript just view it.
var a[];
a.push(number);
alert(a);
I am trying to send an integer values using push but total numbers that I am sending are not fixed. I want to get sum of all numbers which are passing from this array.
If there is any other solution which can be usable in web.
a.push(number)
How can I add all values passing from this loop?
Please correct your JS code:
var
a = [],
sum = 0;
a.push(1);
a.push(2, 5);
for (var i in a) {
sum += a[i];
}
alert('Total sum is: ' + sum);
It will be better if you read complete reference about JavaScript's arrays from https://developer.mozilla.org
var total;
for (i = 0; i < a.length; i++) {
total += a[i] ;
}
alert(total);
a[i] will get the value of the given index which will be incremented with the previous value and the total sum will be stored in total variable
With an array, you can use the Reduce function to sum all elements:
var a = [1, 2, 3, 4, 5];
var sum = a.reduce(function(previousValue, currentValue, currentIndex, arr) {
return previousValue + currentValue;
});
document.write('The total is: ' + sum);

Get the top keyword in an array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an array like this:
var words = { 'love': 4; 'peace': 10; 'war':3; 'family':13; 'dog':19, 'life':7 };
What is the fastest way to get the top 2 keywords (family and dog in this case) ?
Take the keys and sort them with their values descending and take the first 2 elements.
var words = { 'love': 4, 'peace': 10, 'war': 3, 'family': 13, 'dog': 19, 'life': 7 },
top2 = Object.keys(words).sort(function (a, b) {
return words[b] - words[a];
}).slice(0, 2);
document.write('<pre>' + JSON.stringify(top2, 0, 4) + '</pre>');

Categories

Resources