How to merge and add inner array of numbers in javascript? [duplicate] - javascript

This question already has answers here:
How to sum elements at the same index in array of arrays into a single array?
(7 answers)
Closed 3 years ago.
I am working with a multi-dimensional array.
the following is my array:
let arr = [[1,2,3],[1,2,3],[1,2,3]];
the length of the inner arrays will always be the same.
I want create a function to add all the arrays elements together with their respective elements and create a new array with the result.
so my desired output is
result =[3,6,9];

You can use nested for loop for that.
let arr = [[1,2,3],[1,2,3],[1,2,3]];
let res = Array(arr[0].length).fill(0);
for(let i = 0;i<arr[0].length;i++){
for(let j = 0;j<arr.length;j++){
res[i] += arr[j][i]
}
}
console.log(res)

Related

How can I create an array containing 1...X without loop [duplicate]

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Closed 20 days ago.
how creating a JavaScript array containing 1 through to x where x is only known at runtime without the loop.
var arr = [];
for (var i = 1; i <= x; i++) {
arr.push(i);
}
This is a duplicate of this issue
here is the answer anyway
const arr = [...''.padEnd(N)].map((_,i)=>i+1)

Fastest and Most Efficient way to check for duplicates in a javascript array [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
In Javascript, how do I check if an array has duplicate values?
(9 answers)
Checking for duplicate strings in JavaScript array
(13 answers)
Closed 5 months ago.
I am writing a javascript function that takes a nested array and returns the numbers that occurs more than once in that array.
I believe my function is accurate (meaning that it passes their "Correctness test" ) but i am after efficiency, how efficient is this code?
For example - Lets call the name of the function deepSort(nestedArray) where nestedArray is the nested array parameter
function deepSort(nestedArray) {
const flatArr = nestedArray.flat().sort();
let results = []
for (let i = 0; i < flatArr.length - 1; i++) {
if (flatArr[i + 1] == flatArr[i]) {
results.push(flatArr[i]);
}
}
return (results.filter((item, index) => results.indexOf(item) === index)).join()
}
const a = deepSort([[1,3,4,5], [4,7,9,1,3], [2,3,5], [1,2,3,4]]) // Returns 1,2,3,4,5
console.log(a);
const b = deepSort([[1,2,3], [4,5], [6,7,8], [2,9,0]]) // Returns 2
console.log(b);
const c = deepSort([[2,7,9], [4,3], [9,6,5], [1,4,3]]) // Returns 3,4,9
console.log(c);
Can this code be optimized any more for speed and efficiency when handling extremely large values of data?

When uniquely updating an object in an array in Javascript, the objects values are all changing [duplicate]

This question already has answers here:
How to update one Javascript object array without updating the other [duplicate]
(3 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I currently have an array of objects called posts.
for(var i = 0; i < posts.length; i++){
let post = posts[i]
let { item, category } = post
let postCollections = categories[category]
for(var col in userCollections[category]){
let items = userCollections[category][col].items
if(items && col){
postCollections[col]['item'] = item
console.log("HERE!, item)
if(item in items){
postCollections[col]['joined'] = true
}else{
postCollections[col]['joined'] = false
}
}
}
posts[i]['collections'] = postCollections
}
When this is run, the print out for "HERE!" shows the item value is unique. When I print out posts and look at the value for key items they all show the same item.
This was a tough solve. Turns out the line where I set postCollections was using the same object over and over again. Copying the object like this has done the trick:
let postCollections = JSON.parse(JSON.stringify(categories[category]));

Loop is adding too many items to the final array [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.

Convert object key-value pairs to a series of arrays in Javascript [duplicate]

This question already has answers here:
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 2 years ago.
I am new to Javascript. I have a Javascript object like so:
s = {"Toothless":"Dragon","Foo":"Bar"};
I need to convert it into a series of arrays, like so:
out = [["Toothless","Dragon"],["Foo","Bar"]];
This is the reverse of what is discussed in Convert JavaScript array of 2 element arrays into object key value pairs. A JQuery solution is acceptable.
You can map over the items to achieve this:
s = {"Toothless":"Dragon","Foo":"Bar"};
var out = Object.keys(s).map(function(data){
return [data,s[data]];
});
console.log(out);
let s = {"Toothless":"Dragon","Foo":"Bar"};
let out = Object.entries(s);
and you get out as an array of small arrays,
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
var s = {"Toothless":"Dragon","Foo":"Bar"};
var out = [];
for (var key in s){
out.push([key, s[key]]);
}
Try this using jQuery.
var tempArr = [];
s = {"Toothless":"Dragon","Foo":"Bar"};
$.each(s,function(i,v){
tempArr.push([i,v]);
});

Categories