merging two arrays in Javascript [duplicate] - javascript

This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 9 years ago.
I am tying to merge two arrays in JS, and then sort them. The following code will output the two arrays on the page, but ONLY if I remove the "newArr.sort();" line. Otherwise, I get nothing. Can anyone help a newbie here?
function merge(arr1, arr2){
var arr1 = [1,21,13,24,15];
var arr2 = [16,7,81,59,14];
var newArr = "[ ]";
arr1.sort();
arr2.sort();
newArr = arr1+","+arr2;
newArr.sort();
document.writeln(newArr);
}

var arr1 = [1,21,13,24,15];
var arr2 = [16,7,81,59,14];
var arr3 = arr1.concat(arr2);
alert(arr3);
Jsfiddle: http://jsfiddle.net/ZRLSs/

Related

Javascript multidimensional array update one value but got all updated [duplicate]

This question already has answers here:
How to create a 2d array of zeroes in javascript?
(5 answers)
Changing one array element affects other elements
(1 answer)
Closed 1 year ago.
I just found something is interesting in Javascript multidimensional array.
let arr = Array(3).fill([]);
arr[0].push('1');
I thought the result should be arr = [['1'], [], []], but got arr = [['1'], ['1'], ['1']].
If update a value as arr[2][0] = '*', expected array to be arr = [['1'], ['1'], ['*']], but got arr = [['*'], ['*'], ['*']].
So why Javascript multidimensional array work like this? How to just update a value in multidimensional array?
From pichard's comment, I got the right result by doing as following:
let arr = Array(3).fill([]).map(obj => { return [] });
arr[0].push('1');
arr[2][0] = '*';
The result is arr = [['1'], [], ['*']]

creating nested array with fill causes stack overflow [duplicate]

This question already has answers here:
Setting one value in 3D array mutates others values
(2 answers)
Closed 4 years ago.
I'm struggling with a weird Array.prototype.fill behaviour:
const arr = new Array(5)
.fill([]);
arr[0].push('element pushed to 0 only');
console.log(arr[1]); // ['element pushed to 0 only']
All of the items inside the array are filled with this string. I assume all of the [] array-s are pointing to the same array, but I don't see why, could anyone explain?
In fill([]), the argument [] is evaluated before the call to fill.
It's the same as
const subarray = [];
const arr = new Array(5);
arr.fill(subarray);
which is the same as
const subarray = [];
const arr = new Array(5);
for (var i=0; i<arr.length; i++) arr[i] = subarray;
In other words you have the same sub array at all indices: arr[1] is arr[0].
If you want to have different subarrays, you coul do
const arr = Array.from({length:5}, ()=>[]);

Merge 2 arrays in change [duplicate]

This question already has answers here:
Zip arrays in JavaScript?
(5 answers)
Closed 3 years ago.
I wanted to merge two arrays like you can fold 2 packs of cards - in ugly code with for loop and assuming same length so no if's for safety it would look like this:
const arr = [1,2,3];
const rra = [4,5,6];
const result = [];
for(let i=0; i<arr.length; i++){
result.push(arr[i],rra[i]);
}
console.log(result); // Array(6) [ 1, 4, 2, 5, 3, 6 ]
I know there is something similar in String.raw() but it cuts off last element and returns a string, is there equivalent in array ?
String.raw({raw: [1,2,3]}, ...[4,5,6]); //"14253"
You can use .flatMap() for this - This is the same as .map(), followed by .flat()
const arr = [1,2,3];
const rra = [4,5,6];
let newArray = arr.flatMap((ele, i) => [ele, rra[i]]);
console.log(newArray);

Copy property of each element of array1 into array2 [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 4 years ago.
I have array1 that contains 1 char in each element.
What I need, is to get the value of array1[i].charCodeAt(); and put it in array2.
Easy to do it, with a for statement.
for(i=0;i<10;i++){
y[i]= x[i].charCodeAt();
}
I did some research but nothing that explain this case:
Is it possible to populate array2 by some sort of destructuring, or what I am asking is not supported in js? For example:
array1 =['a','b','c'];
array2 = [];
array2 = array1[].charCodeAt.
conole.log('The first char has code ' + array2[0]); // The first letter has code 97.
You aren't creating separate standalone variables, so destructuring isn't what you're looking for - but, you can use .map to transform the first array into the second:
const array1 =['a','b','c'];
const array2 = array1.map(char => char.charCodeAt(0));
console.log(array2);
You can use Array.prototype.map():
const array1 = ['a','b','c'];
const array2 = array1.map(c => c.charCodeAt());
console.log(array2);

Merge two arrays to common values only [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 5 years ago.
I looked at this very popular SO question:
How to merge two arrays of JSON objects
Where the OP has this:
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
Then he says, "I want the output to be:"
var array3 = ["Vijendra","Singh","Shakya"];
My question is "How do you just get Singh as a result?"
var array3 = ["Singh"];
In other words, how do you combine two arrays and only keep data that are common to both? I've looked at merge, concat, intersect, and other options, but I can't seem to get this.
You could filter e.g. the first array array1 from the elements which are also present in the second array2 array.
var array1 = ["Vijendra","Singh"],
array2 = ["Singh", "Shakya"],
res = array1.filter(v => array2.indexOf(v) > -1);
console.log(res);

Categories