This question already has answers here:
Append Multi-Dimension Arrays Horizontally in Blocks
(2 answers)
Closed 4 years ago.
So, I have this 2 arrays:
var num = [1, 2, 3];
var letters = ['a', 'b', 'c'];
I need to combine it to something like this:
var result = [[1, 'a', 'numberandletters'],[2, 'b', 'numberandletters'],[3, 'c', 'numberandletters']]
The third element inside the array is constant when it is being filled. My code so far is this:
for (var x=0; x=3; x++)
result[x] = [num[x], letters[x], 'numberandletters']
But I need to execute it without looping statement.
Is there any function or something I can use to combine these arrays?
var num = [1, 2, 3];
var letters = ['a', 'b', 'c'];
num.map((n,i) => Array(n, letters[i], 'nummberAndLetters'))
Output: As you expected.
If you want it as a function then,
function getCombinedArray(num, letter) {
return num.map((n,i) => Array(n, letters[i], 'nummberAndLetters'));
}
getCombinedArray(num, letters);
Okay. This is what it will be when you don't want to use loop.
const num = [1, 2, 3]
const letters = ['a', 'b', 'c']
let result = [
[
num[0],
letters[0],
'numberandletters'
],
[
num[1],
letters[1],
'numberAndLetter'
],
[
num[2],
letters[2],
'numberAndLetter'
]
]
console.log(result)
Related
suppose, array1 = ['B', 'G', 'R', 'A'], array2 is Uint8Array, how to concatinate these two arrays ?
I used var array3 = array1.concat(array2), but the result seems wrong , and array3.length is alwalys 5, regardless of content of array2.
You can do:
var array2 = Array.from(uint8Array);
var array3 = array1.concat(array2);
Your result (array3) must also be a Uint8Array array.
So, in your example the following should achieve what you're looking for:
const array3 = new Uint8Array([ ...array1, ...array2]);
Your code is creating a new array with your four strings followed by the Uint8Array as a single element.
Array.prototype.concat is an odd beast. If you give it arguments that aren't "concat spreadable" (for instance, things that aren't arrays), it includes those values as simple elements in the array it creates.
Typed arrays are not concat spreadable:
const uint8 = Uint8Array.from([3, 4]);
console.log(uint8[Symbol.isConcatSpreadable]); // undefined (and the default is false)
const softArray = [1, 2];
const result = softArray.concat(uint8);
console.log(result.length); // 3
console.log(result[0]); // 1
console.log(result[1]); // 2
console.log(result[2]); // (A Uint8Array containing 3, 4)
You could use spread instead of concat:
const array1 = ['B', 'G', 'R', 'A'];
const array2 = Uint8Array.from([1, 2, 3]);
const result = [...array1, ...array2];
console.log(result); // ["B", "g", "R", "a", 1, 2, 3]
This question already has answers here:
Counting elements in an array and adding them into an object [duplicate]
(2 answers)
Closed 4 years ago.
If I had an array of letters how would I go about turning each letter into an object key with a value of how many there are in that array in JavaScript?
For example:
const array = ['a', 'b', 'c', 'c', 'd', 'a'];
const obj = { a: 2, b: 1, c: 2, d: 1};
Objects can be indexed very similarly to arrays in JavaScript, like so:
const obj = {};
array.forEach((element) => {
//Check if that field exists on the object to avoid null pointer
if (!obj[element]) {
obj[element] = 1;
} else {
obj[element]++;
}
}
you can simply use Array.reduce() to create a frequency map :
const array = ['a', 'b', 'c', 'c', 'd', 'a'];
let result = array.reduce((a, curr) => {
a[curr] = (a[curr] || 0)+1;
return a;
},{});
console.log(result);
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Compare 2 arrays which returns difference
(10 answers)
Closed 4 years ago.
I need to find the number of items in two arrays which are not duplicate.
Eg here the answer is 1:
const array1 = ['a', 'b', 'c', 'c']
const array2 = ['a', 'b', 'c']
Eg here the answer is 2:
const array1 = ['a', 'b']
const array2 = ['a', 'x', 'y']
My solution works for some inputs but not all:
function something(a, b) {
let aArray = a.split("");
console.log(aArray);
let bArray = b.split("");
console.log(bArray);
aArray.forEach((aItem, aIndex)=> {
console.log(aItem)
bArray.forEach((bItem, bIndex)=> {
console.log(bItem);
if(aItem === bItem) {
console.log(aIndex, bIndex);
aArray[aIndex] = "-";
bArray[bIndex] = "-";
}
});
});
console.log(aArray);
console.log(bArray);
const aRes = aArray.filter(item=> item !== "-").length;
console.log(aRes)
const bRes = bArray.filter(item=> item !== "-").length;
console.log(bRes)
const res = aRes + bRes;
console.log(res)
return res;
}
Stealing from this: https://stackoverflow.com/a/33034768/4903754
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
Closed 6 years ago.
var alph = ["a", "b", "c"];
var r = [];
for(var i = 0; i < 5; i += 1) {
r.push(alph);
}
r[0].reverse();
console.log(r);
/* Output
[ [ 'c', 'b', 'a' ],
[ 'c', 'b', 'a' ],
[ 'c', 'b', 'a' ],
[ 'c', 'b', 'a' ],
[ 'c', 'b', 'a' ] ]
*/
/* Expected output
[ [ 'c', 'b', 'a' ],
[ 'a', 'b', 'c' ],
[ 'a', 'b', 'c' ],
[ 'a', 'b', 'c' ],
[ 'a', 'b', 'c' ] ]
*/
There are arrays in an array. The first array should be reversed. I thought r[0].reverse() would do this, but instead this reverses all arrays.
Can someone explain why this happens ?
You are pushing the reference of the array, so updating one will make changes to the rest since it's all are referring single array. Instead push the copy of the original array for copying array use Array#slice method.
var alph = ["a", "b", "c"];
var r = [];
for (var i = 0; i < 5; i += 1) {
// push the exact copy of original array
r.push(alph.slice());
}
r[0].reverse();
console.log(r);
You're not creating an array of new arrays when you push onto r: you're pushing the same array onto r 5 times (it's being passed by reference, not by value). Therefore, any operation on r[0] is really updating alph, which causes all of the other references to be updated, too.
Well actually you can use slice method like #Pranav C Balan suggested but this will fail when the array is multidimensional. You need something like Array.prototype.clone() to secure the functionality. Lets do it.
Array.prototype.clone = function(){
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
var alph = [ 1, 2, 3, 4, [ 1, 2, [ 1, 2, 3 ], 4 ], 5 ],
cloned = [],
sliced = [];
for(var i = 0; i < 5; i += 1) {
cloned.push(alph.clone());
sliced.push(alph.slice());
}
cloned[0][4][2].reverse(); // only the array at index pos 0,4,2 gets reversed
sliced[0][4][2].reverse(); // all sub arrays at index 4,2 get reversed
console.log(JSON.stringify(cloned));
console.log(JSON.stringify(sliced));
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
Working with the following code:
Array0 = ['a', 'b', 'c'];
Array1 = ['c', 'd', 'e'];
Array2 = ['x', 'a', 'd'];
...
/*
doStuff() is a recursive function whose argument is an abitrary length array
containing an arbitrary list of array names
e.g., anArr = ['Array1', 'Array0', 'Array1', 'Array2', ...]
*/
function doStuff(anArr) {
for(i=0; i<anArr.length; i++) {
switch(anArr[i]) {
case('Array0') : Array0.myMethod(); break;
case('Array1') : Array1.myMethod(); break;
case('Array2') : Array2.myMethod(); break;
}
}
}
Is there a way to replace the switch() block with a single statement:
<<array referenced by 'someArray'>>.aMethod() //or
function aFunction (<<array referenced by 'someArray'>>){}
Plain Javascript, please - no jquery or other library.
Thanks
Use an object in the first place.
var foo = {
Array0 : ['a', 'b', 'c'];
Array1 : ['c', 'd', 'e'];
Array2 : ['x', 'a', 'd'];
}
Then you can:
foo[anArr[i]].myMethod();
You can store the actual arrays in the array...
Array0 = ['a', 'b', 'c'];
Array1 = ['c', 'd', 'e'];
Array2 = ['x', 'a', 'd'];
var anArr = [Array0, Array1, Array2];
for(i=0; i<anArr.length; i++) {
anArr[i].myMethod();
}