I have a global array in javascript say
jsonArr = ["location","department","grade"];
now inside my method i am doing this
var newArr = [];
newArr = jsonArr;
var sorted_arr = newArr.sort();
my newArr is getting sorted but problem is along with jsonArr also got sorted i dont want to sort jsonArr
what is the problem can anyone plz help me ?
newArr and jsonArr are referencing the same array in your code (that's what happens when you simply assign one array to another, like you're doing with this statement: newArr = jsonArr;). You need to copy the array first; you can use the slice method for that:
var newArr = jsonArr.slice(0);
var sorted_arr = newArr.sort();
In line newArr = jsonArr; you assing reference of jsonArr to the newArr, which means this two variables will point to the same place in memory (one array). You must copy array explicit before sorting.
newArr = [].concat(jsonArr);
var newArr = $.extend(true, [], jsonArr);
var sorted_arr = newArr.sort();
You need to make a deep copy. Alternatively you can use the Array.slice() method (http://www.w3schools.com/jsref/jsref_slice_array.asp) which actually gives you a better handle.
Hope that helps!!
Related
I have an nested array. Example
let array = [['a','e1'],['b','b1']]
What i want to achive is a new nested array with a copy of one of the array's and a change to that copy.
when i run it though a loop (tried for and foreach) it duplicates the change throughout the entire nested array.
here is an example of the code (note its not key: index and just an example. the actual inside array contains 11 values in total)
let array = [['a','e1'],['b','b1']]
let result = []
for(let x of array){
result.push(x);
if(x[1]==='e1'){
let newRow = x;
newRow[1] = 'e2'
result.push(newRow);
}
}
//result: [[a,e2],[a,e2],[b,b1]]
let needResult = [['a','e1'],['a','e2'],['b','b1']]
Any assistance in this would be greatly appreciated.
Working example of the script : https://stackblitz.com/edit/js-ah1bvf?file=index.js
Thanks
Instead of use let newRow = x;, as #tadman said in the comment you need to use another way like create a new array let newRow = []; //for example
let array = [['a','e1'],['b','b1'], ['c', 'e1']]
let result = []
for(let x of array){
result.push(x);
if(x[1]==='e1'){
const newRow = [];
newRow[0] = x[0];
newRow[1] = 'e2'
result.push(newRow);
}
}
console.log(result)
As #tadman said in the comment :
let newRow = [...x] // works.
I did not select #simons answer though valid as stated in my question the array can be quite large and I don't necessarily know exactly how long it is.
Thanks for the help!
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)
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]
i'm trying to add together the contents of an array (integers).
for example:
var myArray;
var answer;
myArray[0]=2;
myArray[1]=5;
answer=myArray[0]+myArray[1];
answer should equal 7.Could you help me, please? Thank you so much.
You need to initialize your array
var myArray = [];
As you get more values into your array you might consider a loop, example:
var myArray = [];
var answer = 0;
myArray[0]=2;
myArray[1]=5;
for (var i=0;i<myArray.length;i++)
{
answer += myArray[i];
}
console.log(answer);
Take a look at this: http://www.w3schools.com/js/js_loop_for.asp
When I run your code, I get an error.
you need to intialize your variable myArray to be an array.
var myArray = [];
After I do that, answer has the expected value.
You need to declare myArray as an array, otherwise myArray[0] means a property named 0 on undefined (which will probably blow up) rather than an index access.
var myArray = [];
...
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]);