I have two arrays with ids that have linked lengths. By linked lengths I mean that if ArrayA has length = 4 then ArrayB will have the length equal with (ArrayA.length * (ArrayA.length - 1)) / 2 (which means if ArrayA has length = 4 then ArrayB length = 6, if ArrayA has length = 5 then ArrayB length = 10 and so on).
So let's say these are my arrays: ArrayA = [1, 2, 3, 4] and ArrayB = [a, b, c, d, e, f].
I have to create a new array of arrays based on the next logic:
In the end the new array should look as it follows, where the second parameter is a value from the first array and the third parameter is a value from the second array:
[
[uuidv4(), 1, a],
[uuidv4(), 2, a],
[uuidv4(), 1, b],
[uuidv4(), 3, b],
[uuidv4(), 1, c],
[uuidv4(), 4, c],
[uuidv4(), 2, d],
[uuidv4(), 3, d],
[uuidv4(), 2, e],
[uuidv4(), 4, e],
[uuidv4(), 3, f],
[uuidv4(), 4, f]
]
In the end, I should return this kind of array no matter the size of the arrays, but the arrays have some kind of linked length.
I can't do this with a simple mapping because I don't know how to achieve this kind of logic.
The base idea is that ArrayA is an array of team ids and ArrayB is an array of match ids and I need to add two teams id for every match id.
Thank you for your time! If something is unclear, I'll try to explain better.
As I have seen in your image the logic is for each element in the largest array, assign 2 elements from the shortest one without duplication. In order to achieve this the idea is to loop the largest array and assign in a new array the elements of the shortest array using 2 different index (xIndex0, xIndex1).
In the example below you can see how xIndex0 is pointing to the first element to add from the shortest array, and xIndex1 is pointing to the second element to add, we are incrementing those index depending if we have already reached the end of the shortest array.
var x = [1, 2, 3, 4]
var xIndex0 = 0
var xIndex1 = xIndex0 + 1
var y = ["a", "b", "c", "d", "e", "f"]
var result = [];
y.forEach((elem,index) => {
result.push([null, x[xIndex0], elem]); //replace null with everything you need
result.push([null, x[xIndex1], elem]);
xIndex1++;
if(xIndex1 > x.length-1)
{
xIndex0++;
xIndex1 = xIndex0 + 1
}
})
console.log(result);
Related
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
Hey doing drills on sorting and I found something that I don't fully understand.
let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = numbers.sort((a, b)=> b-a);
let sortedLowesttoHighest = numbers.sort((a, b)=> a-b);
console.log(sortedHighesttoLowest);
console.log(sortedLowesttoHighest);
output:
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
how come this outputs only the last function's value twice even though I assigned them to two separate variable?
Arrays are passed by reference. So when you assign to your variable a sorted array and then you sort again, the first variable will also be affected. You can use spread operator to avoid this.
let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = [...numbers.sort((a, b)=> b-a)];
let sortedLowesttoHighest = [...numbers.sort((a, b)=> a-b)];
console.log(sortedHighesttoLowest);
console.log(sortedLowesttoHighest);
//output:
//[ 1, 2, 3, 4, 5 ]
//[ 1, 2, 3, 4, 5 ]
The comparator function works little different than some traditional languages that you might be used to.
In js, the return value of comparator is -1, 0 and 1. Although in lot of cases you can get away with using - minus operator.
Having said that, you're passing array as reference here which is causing the problem.
Try running this:
let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = numbers.sort((a, b)=> a - b);
console.log(sortedHighesttoLowest);
let sortedLowesttoHighest = numbers.sort((a, b)=> b - a);
console.log(sortedLowesttoHighest);
Additionally I'd encourage you to go through here as well
I have two arrays
[10,8,0,5,3]
[2,4,1,1,3]
I would like to sort the first array to decreasing order, so it becomes [10,8,5,3,0]. The first array's original indices [0, 1, 2, 3, 4] after sorted becomes [0, 1, 3, 4, 2] for example, the original number 5 was in 3rd index, after sorted, it comes to the 2 index. Now, I would like to apply the sorted index to the second array [2,4,1,1,3], so it becomes [2, 4, 1, 3, 1] Is there a quick and easy way to do it?
I came up with 2 solutions so far:
construct an object that holds the key value pair, with the keys being the values of the first array, and values are the second array, for example
{'10': 2, '8': 4, '0': 1, '5': 1, '3':3 }`
Then sort the object according to the key values. Then the values will be sorted, then retrieve all the values from the object.
Construct a map with the values of the first array pointing to each of the values of the second array. Sort the map, and retrieve each value.
These two methods seem a bit complicated. I am wondering if there is an easier way such as leverage the array.sort() function
If you zip the arrays together into a single array, where each item contains the ith value from both arrays, you can sort that larger array pretty easily:
const arr1 = [10,8,0,5,3];
const arr2 = [2,4,1,1,3];
const zipped = arr1.map((num, i) => [num, arr2[i]]);
zipped.sort((a, b) => b[0] - a[0]);
console.log(zipped.map(arr => arr[0]));
console.log(zipped.map(arr => arr[1]));
How can I sort a list of lists by order of the last element?
Here is my best attempt so far:
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
mylist.sort(function(a,b){return a[1]-b[1];});
My call to sort has not effect, and mylist remains in the same order.
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
mylist.sort(function(a,b){return a[1].localeCompare(b[1]);});
console.log(mylist)
Use a[1].localeCompare(b[1]) to sort the list in the ascending order or b[1].localeCompare(a[1]) for other way round. This way you will be comparing two strings. You were trying to subtract one string from the other which return NaN.
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
// to sort by 1st NUMBER element; minus also used for object such as date
mylist.sort(function(a,b){return a[0] - b[0];});
// to sort by 2nd STRING element with >.
// strings can be compared based on alphabetical order with > or <,
// but not with a math order operator -, which is supposed to used for comparison between number or date.
mylist.sort(function(a,b){return a[1] > b[1];});
Above mentioned examples gives sorting in ascending order, here I note what I understand for who may need:
to sort in ascending order [1,9,7] to [9,7,1], we could image there is an empty array[], then we'll just put each element one by one to this array in the right order (based on comparison with existing elements).
function(a,b) { return b - a; }
here a is existing one, b is the one we are going to put in the array.
if return > 0 (true) >> [b,a] , we could consider the return value as the order of a, positive/true means a should put later, that's the sort() means.
if return <=0 (false) >> [a,b]
for [1,9,7], the loop will be:
[]
// to put 1
[1]
// to put 9
a = 1, b = 9, b - a > 0 ==> [9,1]
// to put 7
a = 9, b = 7, b - a < 0 ==> [9,7,1]
a = 1, b = 7, b - a > 0 ==> [9,7,1]
function randOrd() {
return (Math.round(Math.random()) - 0.5)
}
A = [0,1,2,3,4,5,6,7]
var B = A.sort(randOrd)
console.log('A=',A)
console.log('B=',B)
output:
a= [ 3, 4, 0, 1, 6, 2, 5, 7 ]
b= [ 3, 4, 0, 1, 6, 2, 5, 7 ]
I expected a to be the original array and b to be sorted. But they are both equal (sorted), why?
Because the Array.sort() method sorts in-place and then returns the array.
The Javascript sort function sorts the array in place, meaning its modifying the original array and returning it:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Because you're running the method 'sort' on var A... which firstly will sort A into an order, and then set that data to B... which is why you get identical answers for A and B