best way to flatten n-level array into 2d array - javascript

I know there are a lot of ways to flatten an array in javascript, but I want to know what's the best way to flatten an n-level array into a 2D array
Input array looks like this : [[[[1,2]]],[2,3]] i need to convert this into [[1,2],[2,3]]
I tried using array.flat() but it flattens only 1 step and I also tried array.flat(Infinity) but it flattens the whole array into 1D array
the problem is am not sure how deeply nested my input array is. I could think of iterating recursively but am looking if js has any optimised&ready-made way of achieving this?

You could combine map and flat(Infinity) methods to flatten each sub-array to 1D.
const flatDeep = data => data.map(e => e.flat(Infinity))
console.log(flatDeep([[[[1,2]]],[2,3]]))
console.log(flatDeep([[[[1,2]]],[2,[[[3, [4]]]]]]))

Iterate the array and then use Array.flat(Infinity) method.
const list = [[[[1,2]]],[2,3],[[3,4]]]
const result = [];
for (value of list) {
result.push(value.flat(Infinity));
}
console.log(result);

Related

What is a proper way to check if an array is in a nested array? [Javascript]

If I have an array const a = [1, 2] and a nested array const nested = [[1,2], [2,3]]
How do I check if array a is in the nested?
I tried using the nested.includes(a), but it doesn't provide the correct output. And I was thinking stringify the array a, but read some comments about we should not compare array using stringify.
So what is a proper way to check if an array is in another array?
includes doesn't work correctly as it compares references - a and nested[0] are different in terms of references.
Take a look at following function:
function includesDeep(array, value) {
return array.some((subArray) => {
return subArray.every(
(subArrayElem, index) => subArrayElem === value[index]
);
});
}
We have to iterate over all elements of given array and check if every element of this sub array is identical to corresponding element from second array (your a). This method detects type mismatches.
You can stringify the arrays to compare whether they are equal in the callback of Array.some :
const a = [1, 2]
const nested = [[1,2], [2,3]]
const containsA = nested.some(e => JSON.stringify(e) == JSON.stringify(a))
console.log(containsA);
if you must compare it without stringification, prepend a unique id to the values and compare that.

Use Array.map on an 2-dimensional Array

So I have a 2-dimensional Array and want to use a "randomBool" function on each of the elements of the elements in the array.
The "randomBool" function just returns a random boolean:
const randomBool = () => Boolean(Math.round(Math.random()));
this would be the 2-dimensional Array, that I would input:
var test = [
["just","some","random","text"],
[1412,"test",1278391]
]
There is a working for-loop nested in a for-loop:
for (let el of test){
for(let i in el){
el[i] = randomBool();
}
}
I tried this:
test.forEach(el => el.map(el2 => randomBool()));
But it didn't work. Why?
You need to use two nested maps.
const randomBools = test.map(outer => outer.map(inner => randomBool()))
forEach is usually intended to iterate over each item in order to perform some kind of side effect without returning anything and without mutating the original array. For example, printing each item to the console.
map, on the other hand, is intended to take an array and return a new array of the same size, with the values transformed in some way, without mutating the original array. For example, uppercase all the words in a list.
Since you want to return a new 2 dimensional from your existing 2 dimension array with some data transformed, you need to nest your map functions. This will map first over the rows (outer), then the columns (inner). The results of the inner maps will be collected into the outer map and you'll be left with a 2 dimensional array with your new values, all without modifying the original array.

How would I convert an array of multi-dimensions into one single array? Javascript

Task: Someone has given you an array all jumbled up! Convert this multidimensional array into a single array.
I know how to convert a 2-dimensional array into a single array.
How would I convert a multidimensional array, into a single array?
My 2d array has an array of its own.
For example, if you were given an array like this, how would I convert this whole array into a single array?
arr = [[1,[2]],[3,[4]],[5,[6]],[7,[8]]] ==> [1,2,3,4,5,6,7,8]
EX:
function mergeArrays(arr) {
var inOne = arr.reduce(function(a,b) {
return a.concat(b); // works well with 2-dimension, but not this problem.
})
return inOne;//output is [1,Array(1),3,Array(1),1,5,Array(1),2,7,Array(1),3]
} // I need just one array. like this => [1,2,3,4,5,6,7,8]
mergeArrays([[1,[2]],[3,[4]],[5,[6]],[7,[8]]]);
// should equal arr = [[1,[2]],[3,[4]],[5,[6]],[7,[8]]] => [1,2,3,4,5,6,7,8]
I guess what I'm asking is how would you convert an array of any dimension, into a single array.
I have used concat and the spread operator already, It works well if I'm dealing with a 2-dimensional array, but not if my 2-dimensional array has an array of its own.
How would you solve this?
You can use recursion with reduce to return flat array.
function mergeArrays(arr) {
return arr.reduce((r, e) => r.concat(Array.isArray(e) ? mergeArrays(e) : e), [])
}
console.log(mergeArrays([[1,[2]],[3,[4]],[5,[6]],[7,[8]]]))

cloning a 2d array using JSON.stringify()

How are 2d arrays cloned using json.stringify and json.pasrse ?I came across this function which does but couldn't get the technique.What are some other methods to achieve the same?
Note: The JSON.stringify() method converts a JavaScript value to a JSON string.
let g2 = arrayclone(this.state.gridfull);// note gridfull is 2d array
function arrayclone(arr) {
return JSON.parse(JSON.stringify(arr));
}
You could use ES6 deestructurtig:
[...arr]
Or you could you Array.from:
Array.from(arr)
Or you could use concat:
[].concat(arr)
Or you could use slice:
arr.slice()
arr.slice(0)
You could create an empty array and iterate over your original one pushing elements to the new one.
I think that's pretty much it.
Hope it helps.

How to distinguish an array from an array of arrays

Is it possible to distinguish an array from an array of arrays or array of objects in jQuery?
var a = [1,2,3];
var a2 = [[12,'Smith',1],[13,'Jones',2]];
var a3 = [{val:'12', des:'Smith', num:1}];
//a = array
//a2 and a3 = multidimensional array
How can I do this?
Thanks
Since you're using jQuery, you can use:
$.isArray(a[0]);
Here's the documentation: http://api.jquery.com/jquery.isarray/
This is definitely not the only way to find out. You could do this in pure JS too, using:
Array.isArray(v[0]);
Very raw way of checking:
function isMultiDimensional(array) {
return array.some(element => Array.isArray(element))
}
This basically checks if any of your elements is also an array
If you consider multidimensional arrays where all elements are arrays, look at the other answers.
This function can solve your problem
function checkArray(arr){
if(!Array.isArray(arr[0])) return 'simple array';
else return 'Not simple array [Array of arrays (or) Array of objects]';
}
checkArray(a); // simple array
checkArray(a1); // Not simple array [Array of arrays (or) Array of objects]

Categories

Resources