How to concat all this array into a single array:
[Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(2)]
You can use ES6's spread:
var arrays = [[1, 2], [3, 4], [5, 6]];
var res = [].concat(...arrays);
console.log(res);
Use reduce and concat
var output = arr.reduce( (a, c) => a.concat(c), []); //assuming arr is the input array
Edit
As #TJ mentioned in his comment, that above solution will create some intermediate arrays along the way, you can try (concat without spread)
var output = [].concat.apply([], arr);
or
var output = Array.prototype.concat.apply([], arr); //avoiding usage of another unnecessary array `[]`
var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];
console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]
If you have an array of array you can do like so :
let bigArray = new Array();
arrayOfArray.forEach((arr) => {
bigArray.concat(arr);
});
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]
Given an array of arrays, how do I convert this to a JavaScript object with the condition that the first element of each array of the internal arrays will be a key of a new JavaScript object, the subsequent element would be the value?
And if there is more than one occurrence of the element in the first position of the internal arrays only create a single key corresponding to this element.
For example:
var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]
should return:
var obj = {a: ["b", "e"], c: ["d"]}
Here there are 2 occurrences of a within arr therefore only a single key a was created in obj along with c
Using Array.prototype.reduce function, you can accomplish this as follows.
var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']];
const output = arr.reduce((acc, cur) => {
acc[cur[0]] ? acc[cur[0]].push(cur[1]) : acc[cur[0]] = [ cur[1] ];
return acc;
}, {});
console.log(output);
This is an alternative:
var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]
const obj = {}
arr.forEach(([k, v]) => obj[k] = [...obj[k] ?? [], v])
I would like to run through every item in a 1D array and perform an indexOf on another 1D array to determine where it matches.
If I have:
Array 1 = ["a","d","e"]
Array 2 = ["a","b","c","d","e","f"]
I would like to transform Array 1 from values into match locations where it would become: [0,3,4].
I tried the equation below, but it didn't work. I thought using forEach() I could go through every item in Array 1. Then I could run a function to perform an indexOf() on Array 2 for each item. What am I doing wrong??
var array1 = ["a","d","e"];
var array2 = ["a","b","c","d","e","f"];
var array1count = array1.forEach( function (e) { array2.indexOf( e )});
Logger.log(array1count)
If array1 has the same order as array2, you could take a closure over the index and use a while loop inside of the callback for mapping found indices.
var array1 = ["a", "d", "e"],
array2 = ["a", "b", "c", "d", "e", "f"],
indices = array1.map((i => v => {
while (array2[++i] !== v) ;
return i;
})(-1));
console.log(indices); // [0, 3, 4]
For not defined order, you neeeither a single loop for gathering the indices and another to map the collected indices.
var array1 = ["a", "d", "e"],
array2 = ["a", "b", "c", "d", "e", "f"],
indices = array1.map(
Map.prototype.get,
array2.reduce((m, v, i) => m.set(v, i), new Map)
);
console.log(indices); // [0, 3, 4]
forEach() returns undefined, you can try using Array.prototype.reduce():
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
var array1 = ["a","d","e"];
var array2 = ["a","b","c","d","e","f"];
var array1count = array2.reduce(function(acc, curr, i) {
if(array1.includes(curr)) //check if the current item is present in array1
acc.push(i);
return acc;
},[]);
console.log(array1count);
I ran this equation and it worked. Seems to be pretty simple and straightforward. Hopefully I'm not missing something here that the other answers are resolving.
var array1 = ["a","d","e"];
var array2 = ["a","b","c","d","e","f"];
var array1count = array1.map( function (item) { return array2.indexOf(item) });
Logger.log(array1count)
For instance, if I have two arrays that look like this:
var array1 = ['a','b'];
var array2 = [1, 1];
The output array should be:
var newArray = ['a:1', 'b:1']
You could use map like this:
var array1 = ['a','b'], array2 = [1, 1];
var newArray = array1.map((e, i) => `${e}:${array2[i]}`);
console.log(newArray);
You could map the value of the iterating array and from the other array the value of the actual index.
var array1 = ['a', 'b'],
array2 = [1, 1],
result = array1.map((a, i) => [a, array2[i]].join(':'));
console.log(result);
The same with an arbitrary count of arrays
var array1 = ['a', 'b'],
array2 = [1, 1],
result = [array1, array2].reduce((a, b) => a.map((v, i) => v + ':' + b[i]));
console.log(result);
If you are willing to use lodash you can do this very easily with zipWith. It takes arrays and combines the values grouped by index according to a function you provide:
var newArr = lodash.zipWith(array1, array2, (arr1val, arr2val) => `${arr1val}:${arr2val}`);
I have a map that looks like (it's not constant and there could be more subarrays)
var mMp= new Map([
[ "A", [1, "r"] ],
[ "B", [2, "d "]]
]);
I am trying to get to:
var ks = "A, B"
var vs1 = "1, 2"
var vs2 = "r, d"
I could do
mMp.forEach( (val, key) => {.....};
where I add the stuff manually, but I'd have to check for the last value. I also thought about
Array.from(mMp.keys()).join(", ");
but that also would not help with the values, i guess. And it's less efficient, although I'm not too worried about efficiency here.
What's the best way I can get those 3 sets for strings?
Thank you!
Array.from is indeed the way to go. For the values, use .values() instead of .keys() and the callback:
var mMp = new Map([
["A", [1, "r"]],
["B", [2, "d"]],
// …
]);
var ks = Array.from(mMp.keys()).join(", "); // "A, B"
var vs1 = Array.from(mMp.values(), v => v[0]).join(", "); // "1, 2"
var vs2 = Array.from(mMp.values(), v => v[1]).join(", "); // "r, d"
If you have value arrays of arbitrary lengths, use a loop to create all your vs arrays.
Spread the Map to get the entries, then Array#reduce them, and collect the results to separate arrays using Array#forEach. Array#map the arrays to strings, and destructure the results to separate variables (3 in this case):
const mMp = new Map([["A", [1, "r"]], ["B", [2, "d"]], ["C", [3, "e"]], [ "D", [2, "E"]], ["F", [3, "e"]]]);
const [ks, vs1, vs2] = [...mMp].reduce((r, [k, s]) => {
[k, ...s].forEach((c, i) => r[i] ? r[i].push(c) : r.push([c]));
return r;
}, []).map((arr) => arr.join(', '));
console.log(ks);
console.log(vs1);
console.log(vs2);
The following works for arbitrary numbers of key value pairs and arbitrary lengths of value arrays:
var mMp = new Map([
["A", [1, "r"]],
["B", [2, "d "]]
]);
const keys = Array.from(mMp.keys())
const vals = Array.from(mMp.values())
.reduce((p, c) => c.map((v, i) => [...(p[i] || []), v]), [])
const [ks, ...vs] = [keys, ...vals].map(a => a.join(", "))
console.log(ks, vs[0], vs[1]);
// "A, B", "1, 2", "r, d "
The .reduce bit is a somewhat naive implementation of the zip function available in various libraries. If you can use _.zip from lodash, it's a good idea to just use that.