I have an array like this:
var arrayTemp = [
{"0":["Z",59]},
{"1":["D",53]},
{"2":["6",26]},
{"3":["3",19]},
{"4":["Y",10]},
{"5":["H",7]},
{"6":["G",5]},
{"7":["2",5]}
];
I need an output similar to the below one,
var arrayTemp = [
{"Z":59},
{"D":53},
{"6":26},
{"3":19},
{"Y":10},
{"H":7},
{"G":5},
{"2":5}
];
How do I achieve this? I would like this to be achieved with the help of json, underscore or JavaScript.
Using Array.prototype.map() you could iterate trough each element of the original array and create the required objects, returning them as new elements in a new array.
var newArray = arrayTemp.map(function(e, index) {
var x = {};
x[e[index][0]] = e[index][1];
return x;
})
DEMO - Using Array.prototype.map() to create the new array
Something like this:
var newArray = arrayTemp.map(function(e) {
var index = Object.keys(e).shift(),
innerElement = e[index],
ret = {};
ret[innerElement[0]] = innerElement[1];
return ret;
})
JsFiddle to test.
With underscore:
var newArr = _.map(arrayTemp, function(item){
for (var i in item){
var o = {};
o[item[i][0]] = item[i][1];
return o;
}
});
Although #François_Wahl's solution is the better one in my esteem using the native Array.prototype.map().
Related
var arrayA = [ {"name":"sachin","location":"mum"} ];
var arrayB = [ {"name":"Ganguly","location":"mum"} ];
var newArray = arrayA.push(JSON.stringify((arrayB[0].name)));
console.log(newArray); console.log(arrayA);`
if you dont want to create new array then:
var arrayA = [ {"name":"sachin","location":"mum"} ];
var arrayB = [ {"name":"Ganguly","location":"mum"} ];
arrayA[0].name = arrayB[0].name;
console.log(arrayA);`
Since it's an object array and assuming more than one element in future, you need to filter out ganguly object and add it to newArray, and to remove sachin object, you can use the same filter function.
var gangulyArr = arrayB.filter(function(el) {
return el.name === "Ganguly";
});
var newArray = arrayA.concat(gangulyArr);//gangulyArr has all objs named
// ganguly, even if its one
arrayA = arrayA.filter(function(el) {
return el.name !== "sachin"; // to remove sachin from original array
});
If you want to write less code, prefer underscore, it has great methods for these - find, remove, reject, pluck etc.,
var gangulyObj = _.find(arrayB, 'name', 'Ganguly');
var newArray = arrayA;
if(gangulyObj) {
newArray.push(gangulyObj);
}
arrayA = _.reject(arrayA , function(el) { return el.name === "sachin"; });
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)
Here is my function:
function RemoveOutputKeys(array){
var temp = array;
for(var object in temp){
delete temp[object]['statusCode']
delete temp[object]['statusResponse']
}
console.log(array)
if(temp == array)
console.log("how is this possible?!?!!?!?!")
return temp
}
and here is the input I am providing,
array = [{'statusCode':400},{'statusCode':200}]
It makes sense for temp to get updated but I don't want the array to get updated. How can i fix this issue?
Thanks
Use Array.prototype.filter() instead of for in
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
function RemoveOutputKeys(array) {
return array.filter(function(myArray) {
if (!myArray['statusCode'] && !myArray['statusResponse']) {
return myArray;
}
});
}
var originalArray = [{'statusCode':400}, {'statusCode':200}, {'test': 'test'}];
var tempArray = RemoveOutputKeys(originalArray);
console.log(originalArray, tempArray);
https://jsfiddle.net/3kbypvcs/2/
If you want create new array instead of alias/reference use:
var newArray = oldArray.slice();
I have the next key:value array -
[["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]]
And I would like to make an array out of it but only with the values of it and also to keep the order of the values, meaning the new array should be like this -
[76,73,59,52,37,7,5,5,3,2,2]
I've tried to find a way to do that but failed miserably,
Thanks in advanced for any kind of help
You can use map:
var arr1 = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]];
var arr2 = arr1.map(function(v){ return v[1] });
var arr = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]];
var result = [];
arr.forEach(function(val,index){
result.push(val[1]);
});
alert(JSON.stringify(result));
No need of looping through the array, you can use regex in your case to extract all the values from the nested array.
var target = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]];
var result = target.toString().match(/\b\d+\b/g);
console.log(result);
document.write(result);
var res_list = [];
var ori_list = [["key1",76],["key2",73],["key3",59],["key4",52],["key5",37],["key6",7],["key7",5],["key8",5],["key9",3],["key10",2],["key11",2]];
for( var i=0, len=ori_list.length; i<len; i ++ ) {
res_list.push( ori_list[i][1] );
}
I want to merge values of multiple arrays in one object to one array.
For instance:
Object:
- alpha: Array[3]
0: "vatG4d6mcjKbpfuAm"
1: "xkQrKEsfwuYPkDcdz"
2: "GDg9chZnDGrbLXWGS"
- bravo: Array[1]
0: "53LEcQ5MoYXFyvktf"
- …
The result should be:
["vatG4d6mcjKbpfuAm", "xkQrKEsfwuYPkDcdz", "GDg9chZnDGrbLXWGS", "53LEcQ5MoYXFyvktf"]
I did this with a simple for loop iterating over the elements, but I am concerned about the performance. Is this possible with a simple jQuery or underscore.js function?
Any help would be greatly appreciated.
There's no need to use a library for this.
For two arrays use concat:
var arr = obj.alpha.concat(obj.bravo);
For more than two arrays use a loop:
Either with concat again
var arr = [];
for (var k in obj) {
arr = arr.concat(obj[k]);
}
Or using the push.apply method
var arr = [];
for (var k in obj) {
arr.push.apply(arr, obj[k]);
}
DEMO
Make a function using this information so you don't need to repeat code:
function mergeObjectArrays(obj) {
var arr = [];
for (var k in obj) {
arr.push.apply(arr, obj[k]);
}
return arr;
}
var arr = mergeObjectArrays(obj);
with jquery you can use merge
var newArray = $.merge(array1, array2);
with underscore you can use union
var newArray = _.union(array1, array2);
You can concat the arrays using pure javascript like this:
var obj =
{
alpha: ["vatG4d6mcjKbpfuAm", "xkQrKEsfwuYPkDcdz", "GDg9chZnDGrbLXWGS"],
bravo: ["53LEcQ5MoYXFyvktf"]
};
var obj.charlie = obj.alpha.concat(obj.bravo);
// obj.charlie = ["vatG4d6mcjKbpfuAm", "xkQrKEsfwuYPkDcdz", "GDg9chZnDGrbLXWGS", "53LEcQ5MoYXFyvktf"]