How can I check if an array contain another array (ANGULAR)? - arrays

I'd like to know if there's a way to understand if an array contain another array inside him. I ask this question because I'm trying to loop throught two or plus nested arrays but first I need to check this in Angular.
Thanks in advance for the help

var a = [[1,2,3],[4,5,6]]
console.log(Array.isArray(a[0]))
You can check this using Array.isArray function.

There are many ways this can be accomplished, but it depends on the size of the parent array, how deeply nested it's elements are, how does much does performance matter, etc.
If your array only goes one level deep (inner arrays don't contain arrays), you can use these methods:
var arr = [[1,2,3], 'foo', 4, ['foo', 'bar']];
// use .some() to test elements
arr.some((element) => Array.isArray(element));
// returns the index of the first found array, or -1 if no arrays are present
arr.indexOf((element) => Array.isArray(element));
This article gives a pretty good overview of all options, including the performance of each.

Related

Typescript - getting map keys by its values

I have a Map<string, boolean>. I want to extract the keys to an array based on their values. I want to end up with two string arrays; one being keys whose values are false and one being keys whose values are true.
I tried to filter them like this:
const trueKeys = [...myMap.entries()].filter(it => it[1] === true).map(it => it[0]);
const falseKeys = [...myMap.entries()].filter(it => it[1] === false).map(it => it[0]);
But it requires iterating over the entries twice for each array. Is there a better way to achieve this?
I don't think iterating over a map's entries twice vs once is a big deal, as it's hard for me to imagine a situation where changing that would make the difference between code that performs poorly and code that performs well (like running away from a tsunami; you're either too close or far enough away, and running is almost certainly not changing that).
Still, if you want to traverse only once, you can do so:
const trueKeys: string[] = [];
const falseKeys: string[] = [];
myMap.forEach((v, k) => (v ? trueKeys : falseKeys).push(k));
console.log(trueKeys, falseKeys);
Here I'm iterating the Map just once, with the forEach() method. Even [...myMap.entries()] iterates the array once before you even try to filter it, so I've avoided this to ensure that we're only traversing once.
And in the callback I push() each key into one of two arrays depending on the value. This mutates the output arrays, and you can rewrite not to do so, but then you'd almost certainly be throwing away the modest amount of performance gained.
Playground link to code

Array manipulation with nested arrays

let names = ['Ayomide',['Tolu',['Tola',['Chuka',['Dan']]]]];
How can I manipulate each element in this nested array. It's all index 0 and 1. Trying to figure out how to loop through this to get the elements individually, thanks
You could use name.flat(Infinity) to flatten it to a single array (Infinity tells it to go as deep as necessary), and then you can just use .forEach or whatever
let names = ['Ayomide',['Tolu',['Tola',['Chuka',['Dan']]]]];
console.log(names.flat(Infinity))

What is the best way to empty a Vector or Array in AS3?

What is the most efficient way to empty an Array or Vector in ActionScript 3?
I've always just re-initialized them:
vector = new Vector.<T>();
array = [];
It doesn't look like there's an empty() function or anything similar.
Is there a better way?
Re-initializing the array is fine in most cases, since the garbage collector will just sweep up the old array. Still, if you want to empty an array without creating a new one you can set array.length = 0
Another option is to use the splice method.
Array::splice documentation
For an array the following call empties it:
array.splice(0);
For a vector the second parameter is enforced, so the call becomes:
vector.splice(0, vector.length);

In CoffeeScript how do you append a value to an Array?

What is the prescribed way to append a value to an Array in CoffeeScript? I've checked the PragProg CoffeeScript book but it only discusses creating, slicing and splicing, and iterating, but not appending.
Good old push still works.
x = []
x.push 'a'
Far better is to use list comprehensions.
For instance rather than this:
things = []
for x in list
things.push x.color
do this instead:
things = (x.color for x in list)
If you are chaining calls then you want the append to return the array rather than it's length.
In this case you can use .concat([newElement])
Has to be [newElement] as concat is expecting an array like the one its concatenating to.
Not efficient but looks cool in the right setting.

Array.isDefinedAt for n-dimensional arrays in scala

Is there an elegant way to express
val a = Array.fill(2,10) {1}
def do_to_elt(i:Int,j:Int) {
if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))
}
in scala?
I recommend that you not use arrays of arrays for 2D arrays, for three main reasons. First, it allows inconsistency: not all columns (or rows, take your pick) need to be the same size. Second, it is inefficient--you have to follow two pointers instead of one. Third, very few library functions exist that work transparently and usefully on arrays of arrays as 2D arrays.
Given these things, you should either use a library that supports 2D arrays, like scalala, or you should write your own. If you do the latter, among other things, this problem magically goes away.
So in terms of elegance: no, there isn't a way. But beyond that, the path you're starting on contains lots of inelegance; you would probably do best to step off of it quickly.
You just need to check the array at index i with isDefinedAt if it exists:
def do_to_elt(i:Int, j:Int): Unit =
if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))
EDIT: Missed that part about the elegant solution as I focused on the error in the code before your edit.
Concerning elegance: no, per se there is no way to express it in a more elegant way. Some might tell you to use the pimp-my-library-Pattern to make it look more elegant but in fact it does not in this case.
If your only use case is to execute a function with an element of a multidimensional array when the indices are valid then this code does that and you should use it. You could generalize the method by changing the signature of to take the function to apply to the element and maybe a value if the indices are invalid like this:
def do_to_elt[A](i: Int, j: Int)(f: Int => A, g: => A = ()) =
if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j)) else g
but I would not change anything beyond this. This also does not look more elegant but widens your use case.
(Also: If you are working with arrays you mostly do that for performance reasons and in that case it might even be better to not use isDefinedAt but perform validity checks based on the length of the arrays.)

Resources