I need to convert a nested array into 2D in javascript, somewhat similar to the question answered for python at link
How to convert 2d nested array into 2d array single?
For example, the array
[[[[[[[[
[16,12],[16,13],[16,14]]
],
[[[[[[
[46,42],[46,43]
]]]]],[
[62,58],[62,59],[62,60]
]]]]]],
[103,102]],[[118,114],[118,115],[118,116]]
]
needs to be converted to
[[16,12],[16,13],[16,14],[46,42],[46,43],[62,58],[62,59],[62,60],[103,102],[118,114],[118,115],[118,116]]
Please help, thanks in advance
This is what I tried, finally works after many trials :
function removeNestArray2D(object) {
var result = [];
if (Array.isArray(object)) { // check if object is valid array
for(var i=0; i<object.length; i++) {
if(!Array.isArray(object[i])) { // check is each of array element is a valid array
return object;
}
else {
var tmp = removeNestArray2D(object[i]);
if(tmp.length == 1) {
result = tmp[0];
}
else if (tmp.length == 2 && Number.isInteger(tmp[0]) && Number.isInteger(tmp[1])) {
result.push(tmp);
}
else {
for (var j=0; j<tmp.length; j++) {
result.push(tmp[j]);
}
}
}
}
}
return result;
}
Recursive approach will help here. Check each array item if there are size 2 and both are number values then push to result array otherwise continue iteration recursively.
const arr = [[[[[[[[
[16,12],[16,13],[16,14]]
],
[[[[[[
[46,42],[46,43]
]]]]],[
[62,58],[62,59],[62,60]
]]]]]],
[103,102]],[[118,114],[118,115],[118,116]]
];
const get2dArray = arr => {
const res = [];
const pushRecursive = arr => {
if (arr.length == 2 && arr.every(x => Number.isInteger(x))) {
res.push(arr);
} else {
arr.forEach(pushRecursive);
}
};
pushRecursive(arr);
return res;
};
console.log(get2dArray(arr));
function removeNestArray2D(object) {
var result = [];
if (Array.isArray(object)) { // check if object is valid array
for(var i=0; i<object.length; i++) {
if(!Array.isArray(object[i])) { // check is each of array element is a valid array
return object;
}
else {
var tmp = removeNestArray2D(object[i]);
if(tmp.length == 1) {
result = tmp[0];
}
else if (tmp.length == 2 && Number.isInteger(tmp[0]) && Number.isInteger(tmp[1])) {
result.push(tmp);
}
else {
for (var j=0; j<tmp.length; j++) {
result.push(tmp[j]);
}
}
}
}
}
return result;
}
Related
This function is able to search for a string in an array:
public checkElement( array ) {
for(var i = 0 ; i< array.length; i++) {
if( array[i] == 'some_string' ) {
return true;
}
}
}
How can i use array of arrays in the for loop? I want to pass this to a function that search a string with if condition.
Example input:
array[['one','two'],['three','four'],['five','six']].
You can try the "find" method instead
let arr = [['one','two'],['three','four'],['five','six']];
function searchInMultiDim(str) {
return arr.find(t => { return t.find(i => i === str)}) && true;
}
searchInMultiDim('one');
This is a recursive solution that checks if an item is an array, and if it is searches it for the string. It can handle multiple levels of nested arrays.
function checkElement(array, str) {
var item;
for (var i = 0; i < array.length; i++) {
item = array[i];
if (item === str || Array.isArray(item) && checkElement(item, str)) {
return true;
}
}
return false;
}
var arr = [['one','two'],['three','four'],['five','six']];
console.log(checkElement(arr, 'four')); // true
console.log(checkElement(arr, 'seven')); // false
And the same idea using Array.find():
const checkElement = (array, str) =>
!!array.find((item) =>
Array.isArray(item) ? checkElement(item, str) : item === str
);
const arr = [['one','two'],['three','four'],['five','six']];
console.log(checkElement(arr, 'four')); // true
console.log(checkElement(arr, 'seven')); // false
Try this code:
function checkElement(array){
for(value of array){
if(value.includes("some string")){return true}
}
return false
}
console.log(checkElement([["one","two"],["three","four"],["five","six"]]))
console.log(checkElement([["one","two"],["three","four"],["five","some string"]]))
So my array looks like this:
let array = [
{"object1":1},
{"object2":2},
{"object3":3}
];
What I want to do is to check, for example, whether or not "object1" exists. The way I would prefer is pure Javascript.
I am doing this for large chunks of data and so my code needs to be something like this:
if ("opensprint1" in array){
console.log("yes, this is in the array");
} else {
console.log("no, this is not in the array");
};
NOTE: I have tried to use the (in) function in JS and the (hasOwnProperty) and neither has worked.
Any ideas?
if ("opensprint1" in array){
That check for the array keys, so it would work with:
if ("0" in array){
But actually you want to check if some of the array elements got that key:
if(array.some( el => "opensprint1" in el))
You're trying to filter an array of objects. You can pass a custom function into Array.prototype.filter, defining a custom search function. It looks like you want to search based on the existence of keys. If anything is returned, that key exists in the object array.
let array = [{
"object1": 1
},
{
"object2": 2
},
{
"object3": 3
}
];
const filterByKey = (arr, keyName) =>
array.filter(obj => Object.keys(obj).includes(keyName)).length > 0;
console.log(filterByKey(array, 'object1'));
console.log(filterByKey(array, 'object5'));
That is roughly equivalent to:
let array = [{
"object1": 1
},
{
"object2": 2
},
{
"object3": 3
}
];
const filterByKey = (arr, keyName) => {
// iterate each item in the array
for (let i = 0; i < arr.length; i++) {
const objectKeys = Object.keys(arr[i]);
// take the keys of the object
for (let j = 0; j < objectKeys.length; j++) {
// see if any key matches our expected
if(objectKeys[i] === keyName)
return true
}
}
// none did
return false;
}
console.log(filterByKey(array, 'object1'));
console.log(filterByKey(array, 'object5'));
This might help you
let array = [
{"object1":1},
{"object2":2},
{"object3":3}
];
let targetkey = "opensprint1";
let exists = -1;
for(let i = 0; i < array.length; i++) {
let objKeys = Object.keys(array[i]);
exists = objKeys.indexOf(targetkey);
if (exists >= 0) {
break;
}
}
if (exists >= 0) {
console.log("yes, this is in the array");
} else {
console.log("no, this is not in the array");
}
let array = [
{ "object1": 1 },
{ "object2": 2 },
{ "object3": 3 }
];
let checkKey = (key) => {
var found = false;
array.forEach((obj) => {
if (!(obj[key] === undefined)) {
found = true;
array.length = 0;
}
});
return found;
}
console.log(checkKey("object2"));
In this case, I think one of the most efficient way is to do a for and break like:
let array = [
{"object1":1},
{"object2":2},
{"object3":3}
];
exist = false;
for(let i = 0; i<array.length; i++){
if("object1" in array[i]){
exist = true;//<-- We just know the answer we want
break;//<-- then stop the loop
}
}
console.log(exist);
When iteration finds a true case, stops the iteration. We can't perform a break in .map, .filter etc. So the number of iterations are the less possible. I think this is also the case of .some()
I have one array
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
Now I want to check whether "ghi" and "mno" is there or not in array. If there then what is the value.
This is how to do it:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].includes("mno"));
}
Edit, for old browser you can do it this way:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].search("mno"));
}
Where 0 is equal to true ^^
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function valueOf (array, key) {
var value;
if (array.find(function (item) {
return ([ , value ] = item.split("="))[0] === key
})) {
return value;
}
}
console.log(valueOf(arr, "ghi")); // 3
console.log(valueOf(arr, "mno")); // 9
console.log(valueOf(arr, "foo")); // undefined
Using lodash
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
var r = _.find(arr, function(i) { return i.includes('ghi'); });
alert(r);
DEMO
You could use Array.prototype.find() and String.prototype.includes()
arr.find(function(item) {
if(typeof item === "string" && item.includes("asd")) {
return true;
}
return false;
});
Now if an item was found, you can assume that the string was found in the array.
Loop through the array and check each string.
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var pos_of_ghi = searchStringInArray("ghi", arr );
var pos_of_mno = searchStringInArray("mno", arr );
if(pos_of_ghi ==-1){
alert("ghi not found")
}
else{
alert("pos_of_ghi="+pos_of_ghi);
}
if(pos_of_mno ==-1){
alert("mno not found")
}
else{
alert("pos_of_mno="+pos_of_mno);
}
the best and simple logic is:
arr.find(function(item) {
return (typeof item === "string" && item.includes("ghi"));
});
I have a bi-dimensional array made of 0s and 1s.
I need to 'crop' the array so there are no rows / columns that only have 0s in them.
This is how I created the array.
var image = [];
for (y = 0; y < height; y++)
{
image[y] = [];
}
Image example of the array.
And this is what I need the array to be cropped to.
First you should clean the rows by detecting if a an array is full of zeros.
You can use Array.prototype.every.
Example :
This function return is an array is empty or not.
function isEmpty(arr) {
return arr.every(function(item) {
return item===0;
});
}
And you can write an algorithm that detect each rows from 0 until you have a not empty line. And you make the same thing from the end of the array.
After cleaning the rows, you do the do the same thing for cols, and using the same algorithm by using a function that give you each cols as an array.
Here is a complete example that do the job :
var arr = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,0,0,0,0],
[0,0,1,0,1,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,0,0,1,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
];
function cleanRows(arr) {
var i=0;
var j=arr.length-1;
while(i<arr.length && isEmpty(arr[i])) {
i++;
}
while(j>i && isEmpty(arr[j])) {
j--;
}
return arr.slice(i,j+1);
}
function cleanCols(arr) {
var i= 0, j=arr[0].length-1;
while(i<j && isEmpty(getCol(arr,i))) {
i++;
}
while(j>i && isEmpty(getCol(arr,j))) {
j--;
}
j++;
// clear each line
return arr.map(function(row) {
return row.slice(i,j);
})
}
function getCol(arr,colIndex) {
return arr.map(function(item) {
return item[colIndex];
});
}
function isEmpty(arr) {
return arr.every(function(item) {
return item===0;
});
}
var newArr = cleanRows(arr);
newArr = cleanCols(newArr);
console.log(newArr);
I am a javascript beginner. I need to merge two arrays which contains objects which in turn contain arrays.
I have two arrays
arr1[
{
description : "this is a object",
array : [a.x,"b"]
}
]
arr2[
{
array : [a.z,"b","c","d"]
}
]
I have used the following code to perform the merge
function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}
function combine(obj1,obj2) {
var res = {};
for (var k1 in obj1) {
if (!obj1.hasOwnProperty(k1)) continue;
if (obj2.hasOwnProperty(k1)) { // collision
if (typeof(obj1[k1]) !== typeof(obj2[k1])) throw "type mismatch under key \""+k1+"\".";
if (Array.isArray(obj1[k1])) {
res[k1] = obj1[k1].concat(obj2[k1]);
} else if (typeof(obj1[k1]) === 'string' || obj1[k1] instanceof String) {
res[k1] = arrayUnique(obj1[k1].concat(obj2[k1]));
} else if (typeof(obj1[k1]) === 'object') {
res[k1] = combine(obj1[k1],obj2[k1]);
} else {
throw "unsupported collision type "+typeof(obj1[k1])+" under key \""+k1+"\".";
}
} else {
res[k1] = obj1[k1];
}
}
for (var k2 in obj2) {
if (!obj2.hasOwnProperty(k2)) continue;
if (obj1.hasOwnProperty(k2)) continue; // already handled it above
res[k2] = obj2[k2];
}
return res;
}
var res = combine(arr1,arr2);
This is the result i expect
res = { description : "this is a object", array : [a.x,a.z,"b","c","d"] }
But unfortunately this is the result i get
res = { description : "this is a object", array : [a.x,"b","c","d"]}
a.z is ommited.
When both objects have the same array field you concatenate them (concat append the two arrays one after another), here:
if (Array.isArray(obj1[k1])) {
res[k1] = obj1[k1].concat(obj2[k1]);
If instead of ["a","a","b","b","c","d"] you want to get ["a","b","c","d"] you need to perform the array merge manually.
Check this answer for multiple ways to merge arrays without duplicates.