Check whether array contains array [duplicate] - javascript

This question already has answers here:
Check if an array includes an array in javascript
(3 answers)
Closed 10 months ago.
Welcome,
I need to find whether array contains array
I tried two ways(indexOf and includes),but both returns a negative result.
let myarray = [
[4, 2],
[2, 2],
[2, 2],
[2, 4],
[2, 2],
];
console.log(myarray.includes([4, 2]));//Returns false
console.log(myarray.indexOf([4, 2]));//Returns -1
I then thought of having a foreach loop,and checking the array(using ==),
But for that even console.log([4, 2]==[4, 2]);//Returns false
Please Help-I know this is simple for you,

Use some and Array.isArray. some will return true if any one condition in the callback function is true and use Array.isArray to check if the element is an array
let myarray = [
[4, 2],
[2, 2],
[2, 2],
[2, 4],
[2, 2],
];
const hasNestedArray = myarray.some(elem => Array.isArray(elem));
console.log(hasNestedArray)

Related

How do make a JSON from an array [duplicate]

This question already has answers here:
Convert array to JSON
(12 answers)
Closed 6 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Array:
myArr = [[1, 2, 3], [4, 5, 6]]
Expected output:
newArr = "[[1, 2, 3], [4, 5, 6]]"
I have tried:
myArr.toString()
String(myArr)
myArr = `${myArr}`
What I got by doing the above methods:
'1,2,3,4,5,6'
I gather what you would like to achieve is more or less serialization. We could use JSON.stringify in JavaScript to serialize an Array.
const array = [[1, 2, 3], [4, 5, 6]];
const serializedArray = JSON.stringify(arr));
To deserialize the Array, JSON.parse could be used.
const originalArray = JSON.parse(serializedArray));
JSON.strinify is what you need.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
const myArr = [[1, 2, 3], [4, 5, 6]];
const myArrString = JSON.stringify(myArr);
console.log(`Here is my string: ${myArrString}`);
use JSON.stringify(myArr);
you can find out more on below link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Why is my array remain unchanged after sort? [duplicate]

This question already has answers here:
How to sort 2 dimensional array by column value?
(14 answers)
Sort array of objects by string property value
(57 answers)
Closed last year.
My values in a nested array like in the code and I want to sort it by the item name, but the array remain unchanged after the sort.
let arr1 = [
[88, "Bowling Ball"],
[2, "Dirty Sock"],
[3, "Hair Pin"],
[5, "Microphone"],
[3, "Half-Eaten Apple"],
[7, "Toothpaste"] ]
arr1.sort( (a, b) => a[1] - b[1]);
console.log(arr1);

Most efficient way to flatten Array<Array<T> | T> in JavaScript [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 3 years ago.
I want to create a function that accepts an array of both arrays and literals (or maybe objects) and flattens it to a single dimensional array. For example a valid input would be [5, [2, 3], 7, [9, 0, 1]], and the output of that input should be [5, 2, 3, 7, 9, 0, 1].
This is the code I have so far. There is nothing wrong with it, I just want to make sure it's as efficient as possible (it also needs to be es5 compatible).
function flattenArray(list) {
var result = [];
for (var index = 0; index < list.length; index++) {
result.push(list[index] instanceof Array ? list[index] : [list[index]]);
}
return [].concat.apply([], result);
}
console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));
How about simply using Array.flat
function flattenArray(list) {
return list.flat()
}
console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));
This seems to be second fastest ( based on the test link attached below ) and ES5 compatible
console.log([].concat.apply([],[5, [2, 3], 7, [9, 0, 1]]))
Performace test
Cocerning your code: There is no sense in wrapping single elements into arrays, .concat will handle them correctly, in other words:
[1].concat([2], 2)
just works, there is no need for wrapping 2 into [2]. That turns your code into a oneliner.

String to array of array or elements [duplicate]

This question already has answers here:
Converting a string to JSON object
(10 answers)
Closed 3 years ago.
Is there any in build function in javascript that let's me convert string "[[16, [8, 2], 4], 2, 80]" to an array of array or int [[16, [8, 2], 4], 2, 80]
You can use:
JSON.parse("[[16, [8, 2], 4], 2, 80]")

How to append new array to beginning of multi-dimensional array [duplicate]

This question already has answers here:
How can I add new array elements at the beginning of an array in JavaScript?
(12 answers)
Closed 5 years ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
I have a 2 dimensional array called vArr. It looks like follows...
vArr = [[1, 1], [2, 2], [3, 3]];
What I am trying to do, is move all the array elements along when a new array needs to be appended to the beginning of vArr, and then delete the last element of vArr to preserve its size (in this case 3). So for example, if a new element [4, 4] comes along that I want to append to vArr, the new vArr should look like this..
vArr = [[4, 4], [1, 1], [2, 2]];
[4, 4] has been appended to the beginning, all the other elements have moved along and any remaining elements past the vArr size of 3 (namely [3, 3]) have been removed. Here is my code so far...
var vArr = [[1, 1], [2, 3], [3, 3]];
var newv = [4, 4]; // New array to append
// My attempt at splicing newv to position 0 in vArr array without removing anything
vArr = vArr.splice(0, 0, newv);
// newv logs to the console successfully, however vArr is undefined for some reason
console.log(newv);
console.log(vArr);
// Get rid of final element (doesn't work because vArr is no longer defined from above)
vArr = vArr.pop();
I know there is probably something wrong with the syntax in the splicing line, but I have been unable to find any information online about what is wrong here. Does the splice method have to change if you are splicing arrays into 2D arrays? Or does it not work at all in this instance? Any help is greatly appreciated!
Here you go with the solution https://jsfiddle.net/fkz9ubug/
var vArr = [[1, 1], [2, 3], [3, 3]];
var newv = [4, 4];
vArr.unshift(newv)
console.log(vArr);
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
https://www.w3schools.com/jsref/jsref_unshift.asp
The problem is with assigning the result of vArr.splice(0, 0, newv) back to vArr.
The splice function can also remove items from the array and the return value of splice() is those removed items.
So vArr = vArr.splice(0, 0, newv); should simply be vArr.splice(0, 0, newv);.
You can use unshift() for pushing the new array at the beginning of the original array, and pop() to remove the last element from the array:
var vArr = [[1, 1], [2, 2], [3, 3]];
var arrToPush = [4, 4];
vArr.unshift(arrToPush);
vArr.pop();
console.log(vArr);

Categories

Resources