Add array inside array in Javascript - javascript

How do I push array into a new Array.
For example
var arr = ['one','two','three'];
var newArr = [];
Now I want newArr[0] = ['one','two','three']
I have tried using push function but it pushes all the elements of arr into newArr. I want to push the entire arr as it is in newArr

var arr = ['one','two','three'];
var newArr = [];
newArr.push(arr); //<-- add entire original array as first key of new array

You can write:
newArr[0] = ['one','two','three'];
And this will work. Or use variable:
newArr[0] = arr;
Also, array methods push or unshift will the same way in your situation work:
newArr.push(arr);

Others have answered, so I guess your question is not really clear.
As you put your question, first and only element of newArray should be the arr array, then you use
newArr.push(arr);
as Mitya and Tiij7 said.
However, maybe you meant you want to join (concat) 2 arrays in a new array? Then you would use:
var arr3 = [].concat(arr, newArr);
or
var arr3 = [...arr, ...newArr];
Or you just wanted to clone the initial array? Then use
var newArr = [...arr];

Related

How to Enter multiple items in an array to another array at a specific index?

I have an array
array1 = [1,2,3,6,7,8]
array2 = [40,50]
How can i push items in array2 to array1 to get a result
result = [1,2,3,40,50,6,7,8];
keep in mind its not a simple concatination, need to insert the scecond array in specific index.
array1.splice(3, 0, array1 ); => splice doesnt accept another array.
How can i enter items in diffrent array to a specific index?
Im trying this in angular
array1 .splice(3, 0,...array2);
and getting the im getting spread array doesn't support in tslib
var array1 = [1,2,3,6,7,8]
var array2 = [40,50]
function cobmine(arr1,arr2,index){
var arr3=arr1.splice(0,index);
var arr4=arr1.splice(-index);
return arr3.concat(arr2).concat(arr4)
}
var result=cobmine(array1,array2,3);
console.log(result);
Assuming your env does not support spread syntax for some reason you could stick to ES5 apply technique.
array1 = [1,2,3,6,7,8]
array2 = [40,50]
array1.splice.apply(array1, [3, 0].concat(array2))
console.log(JSON.stringify(array1))
You can use below code to add array at a specific index
const arr1 = [1,2,3,6,7,8]
const arr2 = [40,50]
const index = 3
const newArr = [
...arr1.slice(0, index),
...arr2,
...arr1.slice(index + 1),
]
// [1,2,3,40,50,6,7,8]

Convert array with 5 items into array with 1 item

I have an array called 'xxx' with contains 5 items.
I would like to convert it in to a single array with the name newTableData[].
What is the best way to do this?
You can assign array with 5 elements to the zeroth element of second array
var newArray = [];
newArray[0] = existingArray;
var cars = ["Audi", "Volvo", "BMW", "Bentley", "Maruti"];
var newArray = [];
newArray[0] = cars;
console.log(newArray);
For flattening your initial array, you can just do
const flattenedArray = [].concat.apply([], oldArray);
const newArray = [flattenedArray];
If I'm right, the problem is that you have an Array of Arrays of TableItems. Just use a reduce and concat:
xxx.reduce((acc, arrayWithTableItem) => acc.concat(arrayWithTableItem), []);
This way you take advantage of the fact that concat flattens a single level down, so from this:
[[TableItem], ...[TableItem]]
you end up with
[TableItem, ...TableItem]
It's easy peas from there
[xxx.reduce((acc, x) => acc.concat(x), [])]
if you are using ES6+ you can use array destructuring ...
cont newTableData[0] = [...xxx];

Remove multiple array from other array jquery

I Have 2 array like this
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
how can I remove values in array from arr?
I want to obtain
arr = ["9138214"]
Maybe I can use splice() ?
You can use Array.forEach() to loop over to the array of items and then check that each item exist in array array. If so use splice(). Use simple function and indexOf() as it will work in old browsers and also in IE.
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "91382142"];
var i = arr.length;
while (i--) {
if (array.indexOf(arr[i]) !== -1) {
arr.splice(i, 1);
}
}
console.log(arr);
You can use .filter() for that.
Here is an example:
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "9138238"];
arr = arr.filter(e => !array.includes(e));
console.log(arr)
The code above just filters the arr array and keeps only elements that are not present in the array. The .includes() function that I've used works on these arrays because they contain strings, if you're dealing with objects, you need to find some other way of checking if array contains the element.
If you want to lodash, this can be easily done by the difference function:
https://lodash.com/docs/4.17.10#difference
import {difference} from 'lodash';
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
console.log(difference(arr, array));

Match two Arrays as Object of Array

I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)

How to empty an javascript array?

var arr = [-3, -34, 1, 32, -100];
How can I remove all items and just leave an empty array?
And is it a good idea to use this?
arr = [];
Thank you very much!
If there are no other references to that array, then just create a new empty array over top of the old one:
array = [];
If you need to modify an existing array—if, for instance, there's a reference to that array stored elsewhere:
var array1 = [-3, -34, 1, 32, -100];
var array2 = array1;
// This.
array1.length = 0;
// Or this.
while (array1.length > 0) {
array1.pop();
}
// Now both are empty.
assert(array2.length == 0);
the simple, easy and safe way to do it is :
arr.length = 0;
making a new instance of array, redirects the reference to one another new instance, but didn't free old one.
one of those two:
var a = Array();
var a = [];
Just as you say:
arr = [];
Using arr = []; to empty the array is far more efficient than doing something like looping and unsetting each key, or unsetting and then recreating the object.
Out of box idea:
while(arr.length) arr.pop();
Ways to clean/empty an array
This is perfect if you do not have any references from other places. (substitution with a new array)
arr = []
This Would not free up the objects in this array and may have memory implications. (setting prop length to 0)
arr.length = 0
Remove all elements from an array and actually clean the original array. (splicing the whole array)
arr.splice(0,arr.length)

Categories

Resources