I want to push the same element into 2 different arrays without repeating myself and keeping the code dry. Is there any way of doing this with JS?
var arrayA = [];
var arrayB = [];
var a = "a";
arrayA.push(a)
arrayB.push(a)
Can I combine those 2 last lines into one? I was thinking something like:
[arrayA, arrayB].push(a) ? But this doesn't seem to work
Thanks
A bit of an overkill, but you can wrap them both in an array, and use Array.forEach() to push the item to the original arrays:
var arrayA = [];
var arrayB = [];
var a = "a";
[arrayA, arrayB].forEach(arr => arr.push(a));
console.log({
arrayA,
arrayB
});
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 have an object of values and I am trying to populate two arrays with the keys and values from the object.
My Object:
obj = {19455746: 7476, 22489710: 473}
Loop attempting to append data:
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push[i];
sensorDataArray.push[obj[i]];
}
At the moment the two arrays are printing out as empty. My expected outout would be something like:
sensorNameArray = [19455746, 22489710];
sensorDataArray = [7476, 473];
push is a function, not an array, it uses parenthesis not brackets :
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
The syntax push[] doesn't invoke the function, it tries to access a property of the function object. It doesn't throw an error because in Javascript, functions ARE objects and this syntax is technically valid.
So, just fix the syntax to push() in order to actually invoke the function.
You are using square braces []
but array.push() is a function so use circle braces instead
Try the following code
obj = {19455746: 7476, 22489710: 473};
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
This is working and tested.
A different syntax (more elegant IMO) :
var sensorNameArray = Object.keys(obj)
var sensorDataArray = Object.values(obj)
or :
var sensorDataArray = sensorNameArray.map( key => obj[key] )
Best way to deal with JSON is use lodash or underscore.
_.key() and _.value are functions for your requirement.
Eg.:
obj = {19455746: 7476, 22489710: 473};
sensorNameArray = _.keys(obj);
sensorDataArray = _.values(obj);
If you want to proceed in your way, then you can use parenthesis as push inbuilt function of Javascript for inserting element into array.
Correct is:
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
i have array like this
[["apple","banana"],["monkey"]];
how can i associate key to them like,
[{"fruit":["apple","banana"],"wild":["monkey"]}]
is this possible?
i'm trying something like this
var arr = [["apple","banana"],["monkey"]];
var newArray = [];
for(var i=0;i<arr.length;i++){
newArray["fruit"] = arr[i] //further code i don't know
}
help me th
While you can do that, like this:
var array = [["apple","banana"],["monkey"]];
var update = [
{fruit: array[0], wild: array[1]}
];
console.log(update);
...frankly it seems unlikely that's really want you want.
Very simply you can assign a new name simply
var array = [["apple","banana"],["monkey"]];
var names = ["fruits", "wild"]
var modified = [{names[0]: array[0], names[1]: array[1]}];
If you have a lot of values just use a for loop to iterate and assign value to it.
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!!