Delete first element from each array in javascript - javascript

I have a multi dimensional array like this.
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']]
I want to remove all the first element to get a result like this.
var myArray = [['1','2.33','44'],['1','2.33','44'],['1','2.33','44']]
Please Help me. Thanks

Use .forEach to loop over the nested arrays and then .splice them. Splice will remove the first item in the nested array and effect the current array.
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']];
myArray.forEach(array => array.splice(0,1));
console.log(myArray);
Base on the comment you can also use .shift() function to remove the first item.
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']];
myArray.forEach(array => array.shift());
console.log(myArray);

You can try this
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']];
var done = function(){
console.log(myArray);
};
myArray.forEach(function(array){
array.splice(0,1);
done();
});
Output
[['1','2.33','44'],['1','2.33','44'],['1','2.33','44']];

Related

Is it possible to add an array into another array

I need to add ann array to an existing array.
If i have an array
var array = ["foo", "baah"];
then, what i need to do is to add an array into the existing one. So it ends up looking like
var array = ["foo", "baah", ["newfoo", "newbaah"]];
i need to do it client site, so using javascript or JQuery. Anyone who can help me? If i can't add a array to a array, is i then possible to add an object
Something like
var array = ["foo", "baah", /*myObject containing 2 item*/];
just ask for more info if needed.
Just .push will do it
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
array1.push(array2)
console.log(array1)
const arrOne = [1,2,3];
const arrTwo = [4,5];
arrOne[arrOne.length] = arrTwo;
console.log(arrOne);
You don't need to use .push(), you can use index notation.
Just use push:
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
array1.push(array2);
console.log(array1);
You can do it via ... spread operator.
var array1 = ["foo", "baah"];
var array2 = ["newfoo", "newbaah"];
var array3 = [...array1, array2];
console.log(array3);
.push will mutate your first array but this one doesn't.
Push
You can use push to add one array to another
var a = [1,2]
var b =[3,4]
a.push(b) //[1,2,[3,4]]
unshift
This is similar to push but adds the array to the first
a.push(b) //[[3,4],1,2]
concat
a.concat(b)//[1,2,3,4]
concat returns a new array rather than push and unshift which adds in the existing array

Giving an array of indexes, how to push items from one array to another depending on the indexes that are specified?

I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
Another array with the order it should be in :
var myOrder = [0,2,1];
My resulting array would look like this :
var finalArray = [['Apples',22],['Berry',23],['Orange',55]]
My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!
This is a simple map() that doesn't require anything else
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let final = myOrder.map(i => myArray[i])
console.log(final)
The optimal way appears to me to be:
Initialize empty finalArray
Loop over your myOrder array
2.1. Push myArray[index] to finalArray
Like so:
let finalArray = [];
for(let index of myOrder) {
finalArray.push(myArray[index]);
}
Review the for...of syntax if you're not familiar with it.
You can use splice to insert so long as the same number of elements are present in both the arrays.
You iterate over the myOrder array and then use splice, to which the index of the new array is the current value of the iteration and then use array present in the index position of myArray
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray = [];
myOrder.forEach(function(val, index) {
finalArray.splice(val, 0, myArray[index]);
});
console.log(finalArray);
Easy enough using .reduce:
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
function reorder(array, order) {
return order.reduce((newArray, orderIndex) => {
newArray.push(array[orderIndex]);
return newArray;
}, []);
}
console.log(reorder(myArray, myOrder))
function reorder(arr, order) {
return order.map(function(i) {
return arr[i];
});
}
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
reorder(myArray, myOrder); // => [["Apples",22],["Berry",23],["Orange",55]]
One of way solving this will be
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray;
for (x in myOrder) {
finalArray[x] = myArray[myOrder[x]];
}
This is a beginning level solution. Also you use libraries available for java script such as underscore.js(http://underscorejs.org/) for such operations on Array and Object.
Also you can use ECMA 6, for doing this which will reduce your line of coding.
Example-
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let finalArray = myOrder.map(i => myArray[i])
This is the new way of coding in javascript.
In my point of view, it will be easy if you learn latest version of Java script(ECMAscript 6)

Why pushing array into another array merges the elements instead of putting them in separate array

I have a array into which I push new values iteratively, at the end of each iteration I want the array formed to be inserted into new array.
Ex: if at the end of first iteration array=[1,2,3,4], then bigarray=[[1,2,3,4]].
After 2nd iteration, if array=[5,6,7,8], then bigarray=[[1,2,3,4],[5,6,7,8]] and so on.
So basically bigarray is to contain a list of arrays out of which I can obtain arrays.
ex: bigarray[0] should give me a array [1,2,3,4]
What I am doing now is array.push(some values) and at the end bigarray.push(array). Doing this merges all the values into a single array like this
bigarray=[1,2,3,4,5,6,7,8] out of which I can separate first array and second array.
piece of code:
var array=[];
for(var i=0; i<range;i++){
var arraychart=[];
var jan= resp.ChartDataList[i].jan;
arraychart.push(jan);
var feb= resp.ChartDataList[i].feb;
arraychart.push(feb);
var mar= resp.ChartDataList[i].mar;
arraychart.push(mar);
var apr= resp.ChartDataList[i].apr;
arraychart.push(apr);
var may= resp.ChartDataList[i].may;
arraychart.push(may);
var jun= resp.ChartDataList[i].jun;
arraychart.push(jun);
//var jan= resp.ChartDataList[i].jan;
array.push(arraychart);
alert (arraychart);
}
alert(array);
How do I achieve the above desired result??
You should call array.push in this way (array.push([1,2,3])) instead of (array.push(1,2,3))
var bigarray = [];
bigarray.push( [1,2,3,4] );
bigarray.push( [5,6,7,8] );
console.log(bigarray); // prints [[1,2,3,4],[5,6,7,8]]
EDIT
After seeing your code, you don't have problems in your code, just print the array using console.log instead of alert, because alert will call .toString() of the big array, and flatten it
U can try something like this
bigArrray[bigArray.length] = subArray
But...
bigArrray.push([1,2,3])
...works as well for me

How to remove multiple sequential items of an array - JavaScript

I am curious to know how I can quickly and most efficiently remove a number of items from an array in JavaScript without creating a loop.
EXAMPLE:
var array = [1,2,3,4,5,6,7,8,9];
array.remove[0..4]; //pseudo code
console.log(array);//result would then be [6,7,8,9]
Is there a function for this, or is a custom loop required? Rudimentary question I suppose, but just wondering out of curiosity.
Use Array#splice:
var array = [1,2,3,4,5,6,7,8,9];
array.splice(0, 4); // returns [1,2,3,4]
console.log(array); // logs [5,6,7,8,9]
You could just use .slice() on the array.
var array = [1,2,3,4,5,6,7,8,9];
array = array.slice(5,array.length);
Using filter method
var a = [1,2,3,4,5,6,7,8,9], b = [];
b = a.filter(function(element, index){ return index > 4 });
Output of b[]
[6,7,8,9]

How to use push with sub-arrays?

I have 3 arrays like:
var arr1 = [];
var arr2 = [];
var arr3 = [];
//When I want to add something into array then I use
arr1.push("text");
arr2.push("text");
but is it possible to make something like the following example?
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(item);
is it even possible to do something like that? I have tried but does not work.
There's a fundamental misunderstanding though, arr is an array but you're using it as an associative array, which in JavaScript is better represented with an object {}. for...in is for objects, NOT arrays, the MDN has a warning note about it:
for..in should not be used to iterate over an Array where index order
is important...
I would advice even if index is trivial to use a regular for loop or a forEach.
Consider using the following, more appropiate approach.
var obj = {
group1: ['text1'],
group2: ['text2'],
group3: ['text3']
};
// pushing more strings
obj.group1.push('foo');
obj['group2'].push('baz');
You're treating arr['group1'] as an array (by using .push()), but you haven't declared it as an array.
var arr = [];
arr['group1'] = [];
arr['group2'] = [];
arr['group3'] = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
It seems you're actually looking for Javascript Objects instead of arrays.
Also, you need to create these objects first.
var obj = {group1:[],group2:[],group3:[]};
/* or
var obj = {};
obj.group1 = [];
*/
obj['group1'].push("text1");
// or obj.group1.push("text1");
The for...in structure sets your for variable to the key, not the value. Assuming arr['group1'] is an array, this will work fine:
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(arr['group1'][item]);​

Categories