How to combine array within another array using javascript or jquery? - javascript

I have an array named arr and within that array, I have another array.My question is, how to combine this two array?
var arr=["1","2","[3,4]","5"]
My output should be like this:
1,2,3,4,5
Thanks in advance!

You could use spread syntax ... with map and JSON.parse methods.
var arr = ["1","2","[3,4]","5"]
var result = [].concat(...arr.map(e => JSON.parse(e)))
console.log(...result)

Considering that you have an actual array and not a string you can flatten like this
var arr=["1","2",["3","4"],"5"]
var flat = [].concat(...arr)
console.log(flat)

You can change it to string and further replace the square brackets using replace(/[\[|\]]/g,''):
var arr=["1","2","[3,4]","5"];
var res = arr.toString().replace(/[\[|\]]/g,'');
console.log(res);

If the question is how to flat an array like this [1,2,[3,4],5] or this [1,[2,[[3,4],5]]] into this[ 1, 2, 3, 4, 5 ] here a pretty general and short solution:
var arr = [1, [2, [[3, 4], 5]]];
var newArr = JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
console.log(newArr)
Or .flat if browser supports it:
var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
console.log(arr)

Related

How to convert an array to multiple array

I have an array abc = [1, 2, 3].
How can i convert it to multiple arrays: [1, 2] , [1, 3], [2, 3]
Note: If abc have n items, we will convert to n*(n-1) arrays
you could do something like this:
const combinations = arr =>
arr.flatMap((elX, indexX) =>
arr
.filter((_, indexY) => indexY == indexX)
.map(elY => [elX, elY])
)
the result will be n*(n-1) so for [1,2,3] = [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
Looks like you want to list all kind of combination to be made from original array
you can run code below in console to check if it fits your needs
Note that in code below, i use filter to avoid same value in the same array group
Sorry for my bad english
let arr = [1, 2, 3];
arr = arr.map((currentValue, index, arr)=>{
return arr.filter((val2, idx2) => val2 !== currentValue);
});
document.write(JSON.stringify(arr,null,4));
Edit: i know the question wants 6 arrays, this code above is following the example he gave... This is alternative answer if what he really meant was to find every single unique combination (without mirror effect)

Spread syntax doesn't work to destructive an array

I am new to Javascript and is confused why the following won't work?
var array = [1, 2, 3, 4]
var spread = ...array;
I was expecting it would become 1, 2, 3, 4. Instead, it gave an error message Unexpected token .... Can anyone explain this to me?
Thank you so much!
This is the correct way, however you're not gaining anything doing that.
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);
If you really want to destructure that array, you need destructuring assignment:
var array = [1, 2, 3, 4]
var [one, two, three, four] = array;
console.log(one, two, three, four);
The correct way of doing what you want is:
var array = [1, 2, 3, 4]
var spread = [...array];
The syntax for using spread is:
For function calls:
myFunction(...iterableObj);
For array literals or strings:
[...iterableObj, '4', 'five', 6];
For object literals (new in ECMAScript 2018):
let objClone = { ...obj };
So, based on the syntax, for an array by using spread you are missing the square brackets []:
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);

pushing an array into another array

I have the following arrays.
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[];
How would I push arr1 and arr2 into arr3 such that the result is:
arr3=[[1,2,3],[4,5,6]];
not
arr3=[1,2,3,4,5,6];
which is produced when using the .concat method.
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[];
arr3.push(arr1,arr2);
console.log(arr3);
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3 = [arr1,arr2];
console.log(arr3);
arr3.push(arr1);
arr3.push(arr2);
will do the work.
Anyway just follow http://www.w3schools.com/jsref/jsref_push.asp for further clarifications.
Hope this helps.
You can use push() like in the other answers or this:
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [arr1, arr2];
console.log(arr3);
As others users have posted, the solution at your problem is use .push() method, but i would try to give you more information about these two methods.
I suggest you to read this article, is very useful for me; I recap the main information for you below.
PUSH METHOD
Push method is used when you want add one or more elements, that were input arguments, to the array that invoked the method.
A simply example is the following:
var first_array = [1, 2, 3];
var result = first_array.push(4, 5, 6);
console.log(result); // 6
console.log(first_array ); // [1, 2, 3, 4, 5, 6]
The one thing is not immediately apparent is that it returns the length of the array after adding the new values, not the modified array. (check third line: console.log(result);)
CONCAT METHOD
While push alters the array that invoked it, concat returns a new array with the original array joined with the array/s or value/s that were provided as arguments.
There are a couple of the things to note about concat and how it creates the returned array.
Both strings and numbers are copied into the array, which means that they if the original value is changed, the value in the new array will be unaffected.
This is not true for objects.
Instead of copying objects into the new array, the references are copied instead. This means that if the values of objects change in one array, they will also be changed in the other array, as they are references to the objects not unique copies.
A simply example is the following:
var test = [1, 2, 3]; // [1, 2, 3]
var example = [{ test: 'test value'}, 'a', 'b', 4, 5];
var concatExample = test.concat(example); // [1, 2, 3, { test: 'test value'}, 'a', 'b', 4, 5]
example[0].test = 'a changed value';
console.log(concatExample[3].test); // Object { test: "a changed value"}
example[1] = 'dog';
console.log(concatExample[4]); // 'a'
I have created a fiddle for you with this example.
I hope that will be helpful

multidimensional arrays and function calls in javascript

I am trying to work with a multi-dimensional in the following way
function 2darray(mynum) {
var outarray[];
outarray.push(1, 3, 5);
outarray.push(2, 4, 6);
var inarray[];
for (var i = 0; i < outarray.length; i++) {
inarray.push(outarray[i]);
}
// now i want to pass info to another function
getmyarray(inarray[mynum])
}
function getmyarray(access) {
// and access the passed values here, but am i doing the following correctly, and what do i put where the ?'s are..
xassess = access[ ? ][0];
yassess = access[ ? ][1];
}
There are no multi dimensional arrays in Javascript, so what you have is an array of arrays, also known as a jagged array.
Just omit the second index, and you will send the inner array to the function:
getmyarray(inarray[mynum]);
In the function you have a plain array of numbers, so just access it by a single index:
xassess = access[0];
yassess = access[1];
There are no traditional multidimensional arrays in javascript, only arrays of arrays.
// a literal array
var my2dArray = [
[1, 2, 3],
[4, 5, 6]
];
// a "constructed" array
var my2dArray = [];
my2dArray.push([1, 2, 3]);
my2dArray[1] = [4, 5, 6];
my2dArray[2] = [];
my2dArray[2][0] = 7;
Accessing a 2D array is pretty plainforward too; it just works like a 1D array returning another array.
my2dArray[0] == [1, 2, 3];
my2dArray[0][0] == 1;
my2dArray[0][1] == 2;
my2dArray[1][2] == 6;
thanks bart!!
var my2dArray =[
[1, 2, 3],
[4, 5, 6]
];
works great! and when i pass it into a function
getmyarray(my2darray[mynum])
i can access like you would expect!
function getmyarray(mypassedarray)
{ var x=mypassedarray[0];
and console.log(x); is correct!
..now i'm not sure why,but when i try to use the passed values in the google earth plug-in i get
"error: error calling method on npobject" and that error comes on the range part...investigation in progress..

Javascript: Replace everything inside an Array with a new value

I've got an Array:
var Arr = [1, 4, 8, 9];
At some point later in the code this happens:
Arr.push(someVar);
Here instead of pushing a new value, I want to replace the entire contents of Arr with someVar. (i.e. remove all previous contents so that if I console.logged() it I'd see that Arr = [someVar]
How could this be achieved??
Try:
Arr.length = 0;
Arr.push(someVar);
Read more: Difference between Array.length = 0 and Array =[]?
Try this:
Arr = [somevar];
Demo: http://jsfiddle.net/UbWTR/
you can assign the value just like this
var Arr = [1, 4, 8, 9]; //first assignment
Arr = [other value here]
It will replace array contents.
I hope it will help
you want splice to keep the same instance: arr.splice(0, arr.length, someVar)
You can do like this
var Arr = [1, 4, 8, 9]; // initial array
Arr = [] // will remove all the elements from array
Arr.push(someVar); // Array with your new value

Categories

Resources