How to add numbers inside an array. Total of Array Elements [duplicate] - javascript

This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 1 year ago.
If I have an Array of some numbers.
Ex. var num =[123, 234, 12, 0, 23, 19];
How can I get a total of all these elements = 411;

Try This, it is the most recommended method to use.
Even in SAP -Fiori standard code, this method is used.
var num =[123, 234, 12, 0, 23, 19];
var total = num.reduce((a, b) => a + b, 0);

Related

Javasript array functions with no arguments [duplicate]

This question already has answers here:
Create an array with random values
(24 answers)
Closed 3 years ago.
This is more like a silly question but I have to ask it.
It is a good practice to call an array function like map without arguments?
Let's say I already have an array 'x' on my code with a specified length and I want to make another array with the same length but with different content.
For example:
function generateRandomContent() { ... }
const x = [1, 2, 3, 4, 5]
const y = x.map(() => generateRandomContent())
// or
const z = Array(x.length).fill().map(() => { ... })
Of course I could pass an argument and never use it, but it is there a good way and a bad way to do it?
You should not use .map here. A mapping operation is when you take some input and generate a new output. So you have a relation that looks like this x -> y for a single element, then you apply it to the entire array to generate a new array using the same mapping rule:
const input = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];
//mapping relationship
const toCharacter = x => String.fromCharCode(x);
const result = input.map(toCharacter);
console.log(result.join(''))
If you just want to create a new array based on the length of the original but with totally unrelated content, then you are better off to use Array.from which can create an array with a given size and takes a second argument that will fill it with content:
function generateRandomContent() {
return Math.floor(Math.random() * 100);
}
const x = [1, 2, 3, 4, 5]
const y = Array.from({length: x.length}, () => generateRandomContent());
//or just pass the function reference
const z = Array.from({length: x.length}, generateRandomContent);
console.log(y);
console.log(z);

How to sort positive and negative percentages in an array [duplicate]

This question already has answers here:
How to sort an array of floats in JavaScript?
(4 answers)
Closed 5 years ago.
I have this function but It don't sort my percentage correctly:
var arrayWithTheSortedPrice = [10, 12, 18.5, -56, -5, -12.5];
arrayWithTheSortedPrice.sort(function(a, b) {
return a[1] < b[1] ? 1 : -1;
});
console.log(arrayWithTheSortedPrice)
Its sort like this:
[18.5,12,10,-56,-12.5,-5]
I want this as result:
[18.5,12,10,-5,-12.5,-56]
Your sort function is a little off. You can do this with numbers very easily...
var arrayWithTheSortedPrice = [10, 12, 18.5, -56, -5, -12.5];
arrayWithTheSortedPrice.sort(function(a, b) {
return b - a;
});
console.log(arrayWithTheSortedPrice)
The sort function expects a negative value, a positive value, or zero, and then decides how to sort the array based on that result. This simply says to sort numbers in descending order.

Iterate over an array and get the transformed array as a result [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Return array value with forEach() [duplicate]
(1 answer)
Closed 5 years ago.
So there are a lot of questions about iterating over an array, but I found none that says how to get the transformed array back as the left side variable. I can always do a standard for loop with indicies but I was wondering if I could use something like a .foreach that would return a transformed array.
Psedo example: I have an array points which are made up of an object Phaser.Point
Such that I can write the following code
x = new Phaser.Polygon(points.foreach(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
new Phaser.Polygon takes an array of Phaser.Point objects
In this case, you may want to use Array.prototype.map(). Here is an example from MDN:
var numbers = [1, 5, 10, 15];
var roots = numbers.map(function(x) {
return x * 2;
});
// roots is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
In your case:
x = new Phaser.Polygon(points.map(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
References:
Array.prototype.map()
You can use Array.map. Array.map returns new array.

Javascript - Check if 2 items exist in array [duplicate]

This question already has answers here:
Javascript - check array for value [duplicate]
(3 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
In Javascript, how can I ensure that the array of ages has both ages 10 and 18 and not just one.
var ages = [3, 10, 18, 20];
ages.filter(age => age === 10 || age === 18); // returns 10 and 18
ages.filter(age => age === 10 && age === 18); // returns null
The && doesn't ensure that both exist, as it returns null. I know I can use 2 different ages.find/filter and check the combined result, but I am wondering if there is a more elegant way of doing this in a single statement.
To clarify, in the ages array, if I check for 10 (exists) and 21 (doesn't exist), it should return null or false, as one of them does not exist.
You have to use includes function:
var ages = [3, 10, 18, 20];
console.log(ages.includes(10) && ages.includes(18));
Another method is to use indexOf method:
arr.indexOf(searchElement)
arr.indexOf(searchElement, fromIndex)
var ages = [3, 10, 18, 20];
console.log(ages.indexOf(10)!=-1 && ages.indexOf(18)!=-1);
findIndex is another method that you can use.It actions like indexOf, but there are some differences:
Array.prototype.indexOf() expects a value as parameter. This is usefull for arrays of primitive types,such as Number, String, Boolean.
Array.prototype.findIndex() have a callback function as first parameter. This is usefull specially when you have array of objects.
var ages = [3, 10, 18, 20];
var bool=ages.findIndex(a=>a==10)!=-1 && ages.findIndex(a=>a==18)!=-1;
console.log(bool);

zipping array of data in js [duplicate]

This question already has answers here:
Javascript equivalent of Python's zip function
(24 answers)
Closed 8 years ago.
in python:
data = [50, 52, 54, 56, 58]
answer = list(zip(data[0:],data[1:]))
print answer
[(50, 52), (52, 54), (54, 56), (56, 58)]
How can I obtain the same answer in JS?
var data = [50, 52, 54, 56, 58];
var answer = ??
print (answer);
map's callback argument three arguments. The element from the array, the index of the element in the array, and the array itself:
data.slice(1).map(function(el, index) {
return [data[index], el];
});

Categories