How to get these 2D array elements summed if there are duplicates? - javascript

I have seen a couple of examples, but handling arrays with 2 elements in it and I was wondering what changes would have to be made so that this one gets summed by comparing the first element and calculating the 4th elements
array =
[
[2, 'name1','something',15],
[3, 'name10','something',5],
[5, 'name20','something',20],
[2, 'name15','something',3]
]
Expected Result
array =
[
[2, 'name1','something',18],
[3, 'name10','something',5],
[5, 'name20','something',20]
]
Appreciate your help!
Thanks!

Just update the array indices of the required elements
In my test case, I changed the indices used in the script. The script used would be as follows:
function myFunction() {
var array = [
[2, 'name1', 'something', 15],
[3, 'name10', 'something', 5],
[5, 'name20', 'something', 20],
[2, 'name15', 'something', 3]
]
var result = Object.values(array.reduce((c, v) => {
if (c[v[0]]) c[v[0]][3] += v[3]; // Updated the indices
else c[v[0]] = v; // Updated the indices
return c;
}, {}));
console.log(result);
}
From here, index [0] represents the elements in the first column (2,3,5,2) while index [3] represents the elements in the last column (15,5,20,3). So basically, the script only processed the first and last columns to achieve your desired output.
Output

Related

Array sort and value change at the same time

I have an array below and the first number in each array means order.
What I want to do is, whenever I change the order, it resorts the array and re-index it into 2, 3, 4, 5.
const payments = [
[2, paymentName1, '5%'],
[3, paymentName2, '5%'],
[4, paymentName3, '5%'],
[5, paymentName4, '5%']
];
For example, if I change the first array order from 2 to 6, array becomes the one below.
const payments = [
[2, paymentName2, '5%'],
[3, paymentName3, '5%'],
[4, paymentName4, '5%'],
[5, paymentName1, '5%'],
];
what I currently did was to sort it and take for loop to re-order it. and I want to do it in one loop if possible. Please help me with writing this algorithm.
Thanks in advance!
Edit:
payments.sort((a, b) => a[0] - b[0]);
for (const index in payments) {
payments[index][0] = parseInt(index) + 2;
}
This is my current function. Would there be a better way to do?
thanks!
After you sort, just loop over the array and assign the new order values incrementally. There is no "better" here.
const payments = [
[2, "paymentName1", '5%'],
[3, "paymentName2", '5%'],
[4, "paymentName3", '5%'],
[5, "paymentName4", '5%']
];
function setOrder(index, newOrder) {
payments[index][0] = newOrder;
payments.sort(([a], [b]) => a - b);
for (let i = 0; i < payments.length; i++) payments[i][0] = i + 2;
}
setOrder(0, 6);
console.log(payments);
The time complexity is determined by the call to sort: O(nlogn).
Alternatively, you could use binary search to find the target index where the mutated element should go, and then rotate the array elements accordingly. Then the time complexity will be O(n). Although this has a better time complexity, the overhead of JavaScript code will make that for arrays of moderate sizes you'll get faster results with sort.

Push a dimensional array

Why the answer is undefined in the Second example?
// First
var arr = [
[1, 4, 6],
['alex']
];
var newArr = arr[1];
newArr.push('Peter');
console.log(arr);
// Second
var arr = [
[1, 4, 6],
['alex']
];
arr.push([1]['Peter']);
console.log(arr);
The code [1]['Peter'] is trying to access a key named Peter from the array literal [1]. And it is undefined
Your code is equivalent to this:
var arr = [
[1, 4, 6],
['alex']
];
var tempArray = [1];
var tempValue = tempArray['Peter'] // undefined
arr.push(tempValue);
console.log(arr);
You should change it to: arr[1].push('Peter')
That syntax [1]['Peter'] doesn't do what you might imagine. You're passing an input parameter. It doesn't reference the array pushing it into, it's completely independent. So you're effectively telling JavaScript to first create a new array ([1]), and then try to access an index called "Peter" from within it (["Peter"]), and then push that into the next free index in arr. Clearly that "Peter" index doesn't exist within the new array, which is why it outputs undefined.
Instead you'd have to write it like this, so it pushes to the existing array, which is itself at index 1 of arr:
// First
var arr = [
[1, 4, 6],
['alex']
];
var newArr = arr[1];
newArr.push('Peter');
console.log(arr);
// Second
var arr = [
[1, 4, 6],
['alex']
];
arr[1].push('Peter');
console.log(arr);
The problem is
arr.push([1]['Peter']);
But an array which contains a single element, 1, does not have the property Peter. Arrays generally do not have non-numeric properties (other than those on Array.prototype and Object.prototype)
All you need to do is
var arr = [
[1, 4, 6],
['alex']
];
arr[1].push('Peter');
console.log(arr);

javascript, looping through a multi-array to list the first element of the array

So I feel like I should be able to figure this one out, but for whatever reason, i've having some difficulty with it this morning.
I have an array with multiple arrays inside, and i want to loop through this big array and only list the first element in the smaller arrays.
so my array looks something like this
var array = [
[1, 2],
[1, 3],
[3, 4]
]
So, essentially I want to be able to list, (1, 1, 3). The problem for me is that when i try to approach any for loop, i am able to separate the arrays, but not able to list the first element in each smaller array.
I know this is pretty elementary, and even though i did take a look and did not find much, i do feel like this question has already been asked.
Any help with this would be wonderful.
Much thanks.
You can use map() for creating a modified array
var array = [
[1, 2],
[1, 3],
[3, 4]
];
var res = array.map(function(v) {
return v[0];
});
alert(res)
If you just want to list [1,1,3], then this might be enough:
array.map(function(item) {
return item[0];
});
Cheers,
Karol
How about :
var newArray = [];
array.forEach(function(el) {
newArray.push(el[0]);
});
console.log(newArray);
Just use for(...) instead of others for big array. It is fastest. You can see their speed difference in http://jsperf.com/find-first-from-multiple-arrray
var array = [
[1, 2],
[1, 3],
[3, 4]
], r = [];
for (var i = 0; i < array.length; i++) {
r.push(array[i][0]);
}
console.log(r);

Javascript:: Find differences between array that contains duplicated values to a unique array of that array

I found many posts on stack overflow about that similar subject but none of them solve this issue here.
<script>
//Array GanginaA contains duplicated values.
//Array GanginaB contains only unique values that have been fetched from GanginaA
GanginaA=[0,1,2,3,4,5,5,6,7,8,9,9];
GanginaB=[0,1,2,3,4,5,6,7,8,9];
var hezi=<!--The Magic Goes Here-->
console.log(hezi);
/*
* Expected Output:
* 5,9
*/
</script>
GanginaA will always be longer or identical to GanginaB so there is no reason to calculate by the value of the longer array length.
GanginaB will always contains unique values that taken from GanginaA so it will always be the shorter array length or identical to GanginaA array.
Now it makes it a lot easier to find doubles.
You can use filter to get the elements like below
GanginaA = [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9];
GanginaB = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var hezi = GanginaB.filter(function (item, index) {
return GanginaA.indexOf(item) !== GanginaA.lastIndexOf(item)
});
console.log(hezi.join(" , ")); // 5, 9
the easier I can think of :
var hezi=[];
for (var i=0;i<GanginaA.length;i++){
hezi[GanginaA[i]] = GanginaA[i];
hezi[GanginaB[i]] = GanginaB[i];
}
hezi = hezi.filter (function(el){return el!=undefined;});
does everything in O(n) actions and not O(n^2)
Javascript's objects have hashmap like behaviour, so you can use them kind of like a set. If you iterate over all the values and set them to be keys within an object, you can use the Object.keys method to get an array of unique values out.
function uniqueValues() {
var unique = {};
[].forEach.call(arguments, function(array) {
array.forEach(function(value) {
unique[value] = true;
});
});
return Object.keys(unique);
};
This function will return the unique elements in any number of arrays, passed as arguments.
uniqueValues([1, 2, 3], [ 1, 1, 1], [2, 2, 2], [3, 3, 3]); // [ 1, 2 3 ]
One drawback to this method is that Javascript coerces all keys to strings, you can turn them back into numbers by changing the return statement to:
return Object.keys(unique).map(Number);

How to sort an Array of Array (2D Array) by first sub-array value

I need to order an array composed by sub-arrays.
The array have to be ordered by the first element of each sub-array element
Example:
myArray = [ [1,0],[3,10],[2,5],[4,0] ]
desired output: [ [1,0],[2,5],[3,10],[4,0] ]
How can I achieve this in Javascript?
Thanks,Nk
var myArray = [ [1,0],[3,10],[2,5],[4,0] ];
myArray.sort(); // [[1, 0], [2, 5], [3, 10], [4, 0]]
DEMO
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Use sort
myArray.sort(function(a,b){
return a[0]-b[0]
})
This your result
myArray.sort(function(x, y){ return x[0] > y[0] });
use this code hope ,it will work
Demo for this code

Categories