How to distinguish an array from an array of arrays - javascript

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]

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.

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

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

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

Filter array if element is present in another array based on value

I have an object array like this:
var objectArray = [{id_5:"100"},
{id_1:"300"},
{id_2:"500"},
{id_4:"700"},
{id_3:"200"}];
And a normal array like this:
var normalArray = ["id_2","id_5","id_4"];
I want to subtract every element from the objectArray if there's a matching ID in the normalArray. I then want to order the newly created array by the object's value (lowest value being first).
So for the above example the result would be:
var newObjectArray = [{id_3:"200"},
{id_1:"300"}];
Is it possible to do this without jQuery?
I've seen similar questions like this one: Removing object from one array if present in another array based on value but I haven't been able to find an answer that works. Is it possible to do a compare and remove like this while still keeping the key:value pairs intact? Thanks in advance for any help with this!
You should use filter method, which accepts as parameter a callback function.
Also, you have to use Object.keys() method in order to get the key of each object in objectArray.
To check if an element from objectArray doesn't appear in objectArray, you should use indexOf() method.
To achieve the sorted array, you have to use sort() method.
var objectArray = [{id_5:"100"},
{id_1:"300"},
{id_2:"500"},
{id_4:"700"},
{id_3:"200"}];
var normalArray = ["id_2","id_5","id_4"];
var newArray=objectArray.filter(function(item){
return normalArray.indexOf(Object.keys(item)[0]) == -1;
}).sort(function(a,b){
return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
});
console.log(newArray);
You can first use filter() to remove object with key from other array and then sort to sort result array by objects value.
var objectArray = [{id_5:"100"},{id_1:"300"},{id_2:"500"},{id_4:"700"},{id_3:"200"}];
var normalArray = ["id_2","id_5","id_4"];
var newArray = objectArray
.filter(e => !normalArray.includes(Object.keys(e)[0]))
.sort((a, b) => a[Object.keys(a)[0]] - b[Object.keys(b)[0]])
console.log(newArray)

Concatenating html object arrays with javascript

I'm attempting to merge two arrays made up of html objects. For some reason using .concat() will not work for me.
Here's a simple pen to demonstrate the problem: http://codepen.io/anon/pen/kIeyB
Note: I tried searching for something remotely similar but found nothing that answered my question.
I figure you can do this the ole fashion way using for-loops but I rather not re-invent the wheel.
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
//alert(items.length);
var items2 = x.getElementsByClassName("two");
//alert(items2.length);
items = items.concat(items2);
//alert(items.length);
items and items2 are nodeList or HTMLCollection objects, not arrays. They do not contain a .concat() method. They have a .length property and support [x] indexing, but they do not have the other array methods.
A common workaround to copy them into an actual array is as follows:
// convert both to arrays so they have the full complement of Array methods
var array1 = Array.prototype.slice.call(x.getElementsByClassName("one"), 0);
var array2 = Array.prototype.slice.call(x.getElementsByClassName("two"), 0);
This can be also be done like this:
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("one"));
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("two"));
The allitems variable will be a single javascript Array containing all elements with class one & two.
What you have are HTMLCollections, which although behave like arrays, but are not arrays. See here: https://developer.mozilla.org/en/docs/Web/API/HTMLCollection:
..A collection is an object that represents a lists of DOM nodes..
In your case, you could concatenate these objects together into a new array:
var itemsnew;
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
var items2 = x.getElementsByClassName("two");
itemsnew = Array.prototype.concat.call(items, items2);
Now, if you:
console.log(itemsnew);
Will return:
[HTMLCollection[1], HTMLCollection[1]]
And:
console.log(itemsnew[0][0]);
Will return:
<div class="one"></div>
document.getElementsByClassName doesn't return an array.
It returns NodeList which has length property.

Categories

Resources