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

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

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'], [], ['*']]

Array.push() doesn't work as expected [duplicate]

This question already has answers here:
Copy array items into another array
(19 answers)
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 4 years ago.
I have an array. For test purposes i output its contents like this:
for (var i=0; i<array1.length; i++){
console.log(i + ':' + array1[i]);
}
0:String1
1:String2
Now i have a second array. What i want to do is push the contents of array1, into array2.
I do this with this line:
array2.push(array1);
Unfortunately, the contents aof the first array, exist in only one index of the second array. Separated by commas.
For example, if we use view the contents of the second array after the action it will be something like this:
for (var i=0; i<array1.length; i++){
console.log(i + ':' + array1[i]);
}
0:Old_string1
1:Old_string2
2:Old_string3
3:Old_string4
4:String1,String2
While i would like this outout:
4:String1
5:String2
You should try with:
array2 = array2.concat(array1);
or with ES6 destructuring
array2.push(...array1);
Array.push doesn't do that. You need Array.concat :
var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];
console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]
array.push will push one or more objects to the array. You can not pass a full array in the push() method, or the contents will be counted as one object. To combine the two arrays into one, use concat.
You should use the spread operator (...) to destruct the values held in array1 and push those into array2. Like so:
array2.push(...array1);
This will separate all the strings held in array1 into individual values and then push them in. A nice little bit of syntactic sugar introduced in ES6.
Use push and apply:
const a1 = ["all", "my", "strings"];
const a2 = ["belong", "together"];
Array.prototype.push.apply(a1, a2);
console.log(a1);

how to create 2D array in javascript (dynamic)

var array1 = ["james","bob"];
var array2 = ["name","age"];
i had created let us say two arrays array1 and array2. what i'm doing is now for every element in array1 i want a new array of length 5 for that. for example for "james" i want an array of length 5 and for "bob" i want array if length 5 only. Also array1 is dynamic, not static. How to achieve that?
You can use array#reduce. Reduce will iterate for each name in your array1 and you have aggregator newarr where code will keep inserting an array of 5 elements using newarr.push(Array(5))(Array(5) is a constructor to create an array of 5 elements);
In case you want to give default value you can use array#fill()
var array1 = ["james","bob"];
var newarr = array1.reduce((newarr, name) => {
newarr.push(Array(5));
return newarr;
},[]);
console.log(newarr);

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

Get duplicates from array of objects by value [duplicate]

This question already has answers here:
How to combine an array in javascript
(3 answers)
Closed 6 years ago.
I have an array of objects:
var arr = [
{number: "AL-32021611", b: "7500"},
{number: "AL-32021612", b: "Continental"},
{number: "AL-32021612", b: "R3"},
{number: "AL-32021612", b: "7500"}
];
Is there a way that I can get all the number coincidences and get insted of number values the 'b' values in a var?
for example
//loop
result = ["Continental", "R3", "7500"]
what i want is for example i recive the number and then i search all the coincidences with that number value and what i exactly need is all the values from the coincidences
Using ES6 features:
let result = Array.from(new Set(arr.map(el => el.b)));
or
let result = [...new Set(arr.map(el => el.b))];
Array.from()
Set
Array.prototype.map()
Arrow Functions
Spread Operator ...
Str has a nice one-line answer for you, but you can also do it explicitly with a simple for loop. See below.
As you have it,
result = {"Continental", "R3" , "7500"};
is not a valid object. You could use a for loop and push the b values into a new array that would look like:
result = ["Continental", "R3" , "7500"];
Your for loop would look like:
var result = [];
for(var n of arr) {
result.push(arr[n].b);
}
return result;

Categories