This question already has answers here:
How to calculate the sum of multiple arrays?
(6 answers)
Closed 1 year ago.
I have an array. With each item in array is an array number. And the length of each array is the same. For example:
var data = [[1,2,4,1], [2,2,1,3], [1,1,2,2], ...]
And the result I want to have:
=> res = [4, 5, 7, 6]
res is the result of adding arrays according to the corresponding index. And of course my data may also contain lots of items.
I have referenced through the lodash.unzipWith. But it doesn't seem viable. With any advice. please let me know. Sorry for my weak English
You can use reduce and write something like this, without lodash or anything
const data = [[1,2,4,1], [2,2,1,3], [1,1,2,2]]
const sumArrs = (arrs) => {
return arrs.reduce((prev, curr) => {
return curr.map((num, i) => num + (prev[i] || 0))
}, [])
}
console.log(sumArrs(data))
Related
This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 2 years ago.
with some
function test(arr1,arr2){
return arr1.filter(el1=>{
return arr2.some(el2=>{
return el2 === el1
})
})
}
console.log(test([1,2,3,4],[3,4,5,6]))
with includes
function test(arr1,arr2){
return arr1.filter(item => arr2.includes(item));
}
console.log(test([1,2,3,4],[3,4,5,6]))
Maybe there are better way to solve this task?
You could take a Set for one array and filter the other one.
Basically you need one loop for every array.
function test(arr1, arr2) {
return arr1.filter(Set.prototype.has, new Set(arr2));
}
console.log(test([1, 2, 3, 4], [3, 4, 5, 6]))
A better way would be using a Set to save the numbers in the first array.
Then, iterate over the second array using .forEach and add each item that is in the set:
function getIntersection(arr1 = [], arr2 = []) {
const set = new Set(arr1);
const intersection = [];
arr2.forEach(num => {
if(set.has(num)) intersection.push(num);
});
return intersection;
}
console.log( getIntersection([1,2,3,4], [3,4,5,6]) );
This question already has answers here:
Javascript Concatenate Array to String
(2 answers)
Closed 2 years ago.
My goal is to make numbers into strings.
If my actual = concatenateNumbers(7);
expected = "7"
My code for this would be:
function concatenateNumbers(num1) {
return num1.toString();
}
However, if my actual has 2 or 3 more values, actual = concatenateNumbers(7, 9) or actual = (7, 9 ,1) => the expected is = "79" or "791"
Can anybody give me an idea or hint on how I should approach this?
Use The arguments object converted to a real Array, and use Array.prototype.join() with an empty String:
function concatenateNumbers() {
return [...arguments].join("");
}
var numbersArrays = [
[],
[7],
[7, 9],
[7, 9, 1]
];
numbersArrays.forEach(numbersArray=>{
console.log(numbersArray.join(", ") + " => " + concatenateNumbers(...numbersArray));
});
console.log("1, 2, 3 => "+concatenateNumbers(1, 2, 3));
numbersArrays is just a convenient way to use SO's code snippet, along with "["+numbersArray.join(", ")+"]" to show each numbersArrays's Array as an Array, plus the actual call to the actual function concatenateNumbers.
Edited to make function's arguments actually a list of Numbers using the Spread syntax (...), as pointed out by VLAZ.
It will actually concatenate anything, the best it can...
This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 2 years ago.
I've got an array of sessions defined something like this:
const sessions = [{id: 1, eventYear: "2019"},{id: 2, eventYear: "2018"},{id: 3, eventYear: "2018"}];
and I want to create a new array of objects with just the eventYear "2018"
I tried mapping over the array and if session.eventYear === eventYear return the session record, otherwise return nothing, but got a list of objects 3 long (not 2) with one undefined record. I wanted just 2 records returned.
I have the following working, but it feels uncomfortably non functional and long. I'd appreciate a suggestion for how to make this more concise in modern JavaScript
const sessionsForEventYear = [];
sessions.map(function(session) {
if (session.eventYear === eventYear) {
sessionsForEventYear.push(session);
}
});
Use Array.prototype.filter instead:
const sessions = [{id: 1, eventYear: "2019"},{id: 2, eventYear: "2018"},{id: 3, eventYear: "2018"}];
const sessionsForEventYear = sessions.filter(({ eventYear }) => eventYear === '2018');
console.log(sessionsForEventYear);
This question already has answers here:
Sum of a javascript array returns a string concatenation of all the numbers [closed]
(3 answers)
Closed 3 years ago.
I'm trying to reduce an array of numbers into the sum of all the numbers combined. At the moment I'm using Array.reduce to try and achieve this, but what I'm finding is that this function only stacks the array's values to create one massive number rather than summing them all together.
// Function used to get the sum of all numbers in array
function getSum(total, num){
return total + num;
// Reduce Var
var easternSum = scoreEastern.reduce(getSum);
// Dynamic array based on user input
var scoreEastern = dataSet
.filter(scoreEastern => scoreEastern.Course === 'eastern')
.map(({Score}) => Score);
// Empty array that scoreEastern var is assigned to
var dataSet = [];
Because my array is dynamic, it's based on what the user inputs into a form, there's no set array. But let's say the array is:
var scoreEastern = [10, 20, 30]
The reduce var easternSum will result in the number 102,030. What I want is 60.
I think maybe scoreEastern doesn't have the data that you expect all the time? You mentioned that it is dynamic. This snippet appears to work for the use case you posted in your question.
const scoreEastern = [10, 20, 30];
console.log(scoreEastern.reduce((prev, curr) => prev + curr));
This question already has answers here:
How to get first N number of elements from an array
(14 answers)
Closed 5 years ago.
i would like to get the first 3 elements of an array of variable length. i've sorted my array and i would like to get a Top 3.
here's what i've done :
var diffSplice = this.users.length - 1;
return this.users.sort(this.triDec).splice(0,diffSplice)
my "solution" work only for an array of 4 element ( -1 )
Is there a better way to use the splice method ?
Thanks for your help
You could use Array#slice for the first three items.
return this.users.sort(this.triDec).slice(0, 3);
Don't you want to use a const value for diffSplice like
var diffSplice = 3;
return this.users.sort(this.triDec).slice(0,diffSplice)
try running
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 3));
refer to Array Silce
Fill out the deletecount for Splice:
var sortedArray = this.users.sort(this.triDec);
return sortedArray.splice(0, 3);
check MDN