How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console
Related
I want to create a new 2D array from another 2D array retaining specific columns from the original array that are defined in a variable.
I have a working version that uses hardcoded values of which columns from the original array to retain but I need a version that uses a variable.
var data = [
[1,5,7,8,9,98,56],
[4,7,8,9,2,55,88],
[3,3,4,3,3,24,11]
];
var indexes2Keep = [0,2,6];
data.forEach(function(row) {
slicedData.push( [ row[2], row[4], row[6] ] );
});
Instead of having the columns hardcoded in the array push method how can I use the values of the variable indexes2Keep to give the same result.
thanks
Expected output is:
slicedData = [
[1,7,56],
[4,8,88],
[3,4,11]
];
You can use Array.map/Array.filter:
var data = [
[1,5,7,8,9,98,56],
[4,7,8,9,2,55,88],
[3,3,4,3,3,24,11]
];
var indexes2Keep = [0,2,6];
var slicedData = data.map(function (row){
return row.filter(function(_,i){
return indexes2Keep.indexOf(i) !== -1
})
})
//Alternatively
var slicedData2 = data.map(function (row){
return indexes2Keep.map(function(i){
return row[i]
})
})
console.log(slicedData)
console.log(slicedData2)
Simply call .map on that array to map each index to the element at that index in the row.
data.forEach(function(row) {
slicedData.push(indexes2Keep.map(function(index) {return row[index]}));
});
You could use the map() function for this:
slicedData.push(indexes2Keep.map(index => row[index]));
I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);
How can I change the format of the array? the idea is to place the array2 equal to the array1, I mean the format of square brackets and commas.
that is, change the ":" with "," and the {} with []
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}]
The most appropriate way to do this is probably using the map() method. Using this, you're constructing a new array by manipulating each item of an original array. Learn more here.
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}];
var array1 = array2.map(function (item) {
var key = Object.keys(item)[0];
var value = item[key];
return [key, value];
});
console.log(array1);
// returns [["Sep", 687918], ["Nov", 290709], ["Dic", 9282], ["Ene", 348529]]
This work for you?
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var array2 = {};
array1.forEach(function(element){
array2[element[0]]=element[1];
});
"I mean the format of square brackets and commas"
Square brackets says, that it is an array, and array elements should be separated by commas. Actually, you want to convert the array of arrays to the array of objects. Here is short ES6 solution:
var array1 = [["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var newArray = [];
array1.forEach(item => newArray.push({[item[0]]: item[1]}))
console.log(newArray)
You can do this by using the array .reduce method:
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2 = array1.reduce((arr2, current) => {
arr2.push({[current[0]]: current[1]});
return arr2
}, []);
console.log(array2)
I am creating project using nodejs. I want to convert array of objects into simple array.For example
var test = [ { id: '1111',
type: 'sdfsdf'
},
{ id: 'df45',
type: 'fsdsdf',
}]
I need
var actual = [111,'sdfsdf'], ['df45','fsdsdf'].
I would propose this solution based on a dynamic number of keys:
var arr = test.map(function(obj){
return Object.keys(obj). // convert object to array of keys
reduce(function(arr, current){arr.push(obj[current]); return arr}, []); // generate a new array based on object values
});
This can be done using Array.map() as follows:
var actual = []
test.map(function(object) {
actual.push(objectToArray(object))
})
function objectToArray(obj) {
var array = []
// As georg suggested, this gets a list of the keys
// of the object and sorts them, and adds them to an array
var obj_keys = Object.keys(obj).sort()
// here we iterate over the list of keys
// and add the corresponding properties from the object
// to the 'array' that will be returned
for(var i = 0; i < obj_keys.length; i++) {
array.push(obj[obj_keys[i]])
}
return array
}
The function objectToArray takes any object and turns it into an array so that it can be flexible regardless of the keys within the object.
I have not been able to figure out how to properly accomplish this.
I have a JS array of objects that looks like this:
[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]
I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:
[
"09599",
"KCC",
"000027",
"Johns" ]
The IDs can be dropped entirely. Any help would be really appreciated.
Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this
var keys = ['num', 'name'],
result = [];
for (var i = 0; i < data.length; i += 1) {
// Get the current object to be processed
var currentObject = data[i];
for (var j = 0; j < keys.length; j += 1) {
// Get the current key to be picked from the object
var currentKey = keys[j];
// Get the value corresponding to the key from the object and
// push it to the array
result.push(currentObject[currentKey]);
}
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]
Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.
If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this
var keys = ['num', 'name'];
console.log(data.reduce(function (result, currentObject) {
return result.concat(keys.map(function (currentKey) {
return currentObject[currentKey];
}));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]
You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.
var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];
var filtered = array.map(function(elm){
var tmp = [];
//Loop over keys of object elm
Object.keys(elm).forEach(function(value){
//If key not equal to id
value !== 'id'
//Push element to temporary array
? tmp.push(elm[value])
//otherwise, do nothing
: false
});
//return our array
return tmp;
});
//Flat our filtered array
filtered = [].concat.apply([], filtered);
console.log(filtered);
//["09599", "KCC", "000027", "Johns"]
How about using map :
var data = [
{"num":"09599","name":"KCC","id":null}
{"num":"000027","name":"Johns","id":null}
];
var result = data.map(function(obj) {
return [
obj.num,
obj.name,
obj.id
];
});