Add multiple elements into all arrays that are equal [duplicate] - javascript

This question already has answers here:
How to extend an existing JavaScript array with another array, without creating a new array
(20 answers)
Closed 8 years ago.
$ node
> A = [0, 1, 23]
[ 0, 1, 23 ]
> B = A
[ 0, 1, 23 ]
> A.splice(0, 3)
[ 0, 1, 23 ]
> B
[]
> A
[]
> A = A.concat([1, 2])
[ 1, 2 ]
> B
[]
This is correct. But, is it possible that after calling concat, B array be equal with A?
I know that there is the loop solution, but what other alternatives are there to add multiple elements in multiple arrays that are equal?
BTW, I don't want to modify B directly (A = B = A.concat(...)).

Paul is correct, you could do:
A.push.apply(A,[1, 2]);
For those of you not aware, Array#push accept variable arguments, and Function#apply converts a variable arguments accepting function to an array accepting function.

You can use Array.prototype.splice itself, like this
var A = [0, 1, 23], B = A;
A.splice.apply(A, [A.length, 0].concat([1, 2]));
console.log(A, B, A === B);
// [ 0, 1, 23, 1, 2 ] [ 0, 1, 23, 1, 2 ] true
Here, A.length and 0 represent the starting position at the array and number of elements to remove respectively.
We concatenate that with the actual array of elements to be inserted. So, the arguments being passed to A.splice would look like this
A.splice(A.length, 0, 1, 2);
As splice does in-place operation, A and B still refer the same object.

Related

Create combinations of arrays with values from two arrays

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);

Is it possible to have multiple keys point to the same object?

Basically I want to call myList[i] and get the same value for i = 1, 2, 3, 4 then a second value for 5, 6, 7, 8 and so on. I don't really want to copy-paste the value for 1 into 2, 3, 4.
You can try using this -
myList[Math.floor((i-1)/4)]
where i = 1, 2, 3, 4 ...
But if i starts from 0, then
myList[Math.floor(i/4)]
Adjust the +/- 1 according to your requirements.
Where 4 is the block size to which you need to divide the array with.
You can use an array of objects
const arr = [...Array(4).fill({ value: 1 }), ...Array(4).fill({ value: 3 })];
console.log(arr[0].value);
console.log(arr[2].value);
console.log(arr[4].value);
console.log(arr[6].value);
arr[0].value = 2;
console.log(arr[0].value);
console.log(arr[2].value);
console.log(arr[4].value);
console.log(arr[6].value);
Each element is a reference to the same object.
That's not possible with an array of primitives.

Outputting same value for two separate sorting functions

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

Reducing array of items into a single array list [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 6 years ago.
Below is my array if items that I want to reduce it to a single list of arrays..
var input=[
[
2
],
[
3,
13
],
[
4,
14
],
[
5,
15,
25,
35
]
]
var output=[
2,
3,
13,
4,
14,
5,
15,
25,
35
]
My code:
function reduceArray(item){
for(var i=0;i<item.length;i++){
return i;
}
}
var result=result.map((item)=>{
if(item.length>0){
return reduceArray(item);
}else{
return item;
}
})
which produces the same result.Can anyone please figure out where I'm doing wrong or any other approach to achieve this..Thanks
input.reduce(function(a, x) { return a.concat(x); });
// => [2, 3, 13, 4, 14, 5, 15, 25, 35]
reduce sets the accumulator to the first element (or a starting value if provided), then calls the function with the accumulator and each successive element. The function we provide is concatenation. If we say input is [a, b, c], then the above command will be equivalent to a.concat(b).concat(c). [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) produces a new array by smushing two or more arrays together.
EDIT: Actually, there is another possible answer:
Array.prototype.concat.apply(input[0], array.slice(1));
// => [2, 3, 13, 4, 14, 5, 15, 25, 35]
This directly calls concat with multiple arguments; if input is again [a, b, c], then this is equivalent to a.concat(b, c). apply calls a function with a given receiver and arguments; slice will give us just a part of the array, in this case everything starting from the first element (which we need to chop off since it needs to be the receiver of the concat call).
One liner would be
input = [[2],[3,13],[4,14],[5,15,25,35]];
[].concat.apply([],input);
You can use lodash's flattenDeep()
_.flattenDeep([1, [2, [3, [4]], 5]]);
// → [1, 2, 3, 4, 5]
User concat.check this for more information http://www.w3schools.com/jsref/jsref_concat_array.asp
var input=[[2],[3,13],[4,14],[5,15,25,35]];
var output=[];
for(var i = 0; i < input.length; i++)
{
output = output.concat(input[i]);
}
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
use concat is the perfect way
The concat() method is used to join two or more arrays.
This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.
var newArr = [];
for(var i = 0; i < input.length; i++)
{
newArr = newArr.concat(input[i]);
}
console.log(newArr);

Why A and B are equal after sort()?

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

Categories