I have an array with objects and in each object there is an "items" array. My goal is to combine these "items" into one array.
Goal / Expected Output
[
{ id: 'SUV' },
{ id: 'Compact' },
{ id: 'Gasoline' },
{ id: 'Hybrid' }
]
Sample Array
[
{
"id":"carType",
"items":[
{
"id":"SUV"
},
{
"id":"Compact"
}
]
},
{
"id":"fuelType",
"items":[
{
"id":"Gasoline"
},
{
"id":"Hybrid"
}
]
}
]
You could use Array#flatMap.
const data = [{"id":"carType","items":[{"id":"SUV"},{"id":"Compact"}]},{"id":"fuelType","items":[{"id":"Gasoline"},{"id":"Hybrid"}]}];
const r = data.flatMap(({ items }) => items);
console.log(r);
A one-liner in vanilla JS (earlier than EMCAScript 2019, flatMap is not available, so in case of that...)
[].concat(...arr.map(elt => elt.items))
Something like this?
newArr = []
for (let i = 0;i<arr.length;i++) {
for (let ii = 0;ii<arr[i].items.length;ii++) {
newArr.push(arr[i].items[ii].id)
}
}
console.log(newArr)
I am new in javascript and using nodejs and mongoose query to get a result which I would like to loop through and get some values in another array.
The resultset looks like
[ { _id: 5366e9049cfc825b32966852,
companies:
[ 5ab20bb69cb2754e949a09dc,
5ac5d53983d45353bc6a9c54,
5ac62eeca5421e4cb9abf63e]
},
{ _id: 5b9251f8ae8db624755f4b90,
companies:
[ 5b461c892bb9c81bd3ed4a25,
5b5086196947782fbc873d28,
5b76a6c79dc71a4a12564cc5 ]
}]
The final array should look like --
[ 5ab20bb69cb2754e949a09dc,
5ac5d53983d45353bc6a9c54,
5ac62eeca5421e4cb9abf63e,
5b461c892bb9c81bd3ed4a25,
5b5086196947782fbc873d28,
5b76a6c79dc71a4a12564cc5]
My code--
Model.find().exec(function(err,gdoc){
if(err)
{
callback({err:err,message:"Error looking up company"});
}else
{
for (var i = 0, len = gdoc.length; i < len; i++) {
console.log(gdoc.companies);
}
}
});
I am getting undefined values.
Any help is highly appreciated. Thanks in advance.
The reason why you are getting undefined is that you try to access the non-existing companies property on gdoc. Instead of gdoc.companies, you have to use gdoc[i].companies.
Instead of your loop, you can use Array.prototype.concat together with the spread syntax (...) and Array.prototype.map as follows:
const gdoc = [
{
_id: '5366e9049cfc825b32966852',
companies: [
'5ab20bb69cb2754e949a09dc',
'5ac5d53983d45353bc6a9c54',
'5ac62eeca5421e4cb9abf63e',
],
},
{
_id: '5b9251f8ae8db624755f4b90',
companies: [
'5b461c892bb9c81bd3ed4a25',
'5b5086196947782fbc873d28',
'5b76a6c79dc71a4a12564cc5',
],
},
];
const companies = [].concat(...gdoc.map(doc => doc.companies));
console.log(companies);
Basically you're trying to concatenate all the company fields of the results array. As long as you know that the key is companies, this is an easy reduction.
Arrays have a couple of builtin methods that make transforming them very easy, compared to having to use a for-loop.
Array.forEach(), Array.map(), Array.reduce() and Array.find() are the most frequently used ones.
// Since these id's contain letters as well, they need to be strings.
const data = [
{
_id: "5366e9049cfc825b32966852",
companies:[
"5ab20bb69cb2754e949a09dc",
"5ac5d53983d45353bc6a9c54",
"5ac62eeca5421e4cb9abf63e"
]
},
{
_id: "5b9251f8ae8db624755f4b90",
companies:[
"5b461c892bb9c81bd3ed4a25",
"5b5086196947782fbc873d28",
"5b76a6c79dc71a4a12564cc5"
]
}
];
const companies = data.reduce(( result, item ) => result.concat( item.companies ), []);
console.log( companies );
You can use the following method:
const map = [...[].concat(...arr.map((o) => o.companies))]
var arr = [ { _id: "5366e9049cfc825b32966852",
companies:
[ "5ab20bb69cb2754e949a09dc",
"5ac5d53983d45353bc6a9c54",
"5ac62eeca5421e4cb9abf63e"]
},
{ _id: "5b9251f8ae8db624755f4b90",
companies:
[ "5b461c892bb9c81bd3ed4a25",
"5b5086196947782fbc873d28",
"5b76a6c79dc71a4a12564cc5" ]
}];
const map = [...[].concat(...arr.map((o) => o.companies))]
console.log(map);
How about running a reduce over the array.
const model = [{
_id: "5366e9049cfc825b32966852",
companies: [
"5ab20bb69cb2754e949a09dc",
"5ac5d53983d45353bc6a9c54",
"5ac62eeca5421e4cb9abf63e"
]
},
{
_id: "5b9251f8ae8db624755f4b90",
companies: [
"5b461c892bb9c81bd3ed4a25",
"5b5086196947782fbc873d28",
"5b76a6c79dc71a4a12564cc5"
]
}
];
const reducer = (acc, value) => {
acc.push(...value.companies);
return acc;
};
console.log(model.reduce(reducer, []));
You can do some thing like that!
var docs= [ { _id: "5366e9049cfc825b32966852",
companies:
[ "5ab20bb69cb2754e949a09dc",
"5ac5d53983d45353bc6a9c54",
"5ac62eeca5421e4cb9abf63e"]
},
{ _id: "5b9251f8ae8db624755f4b90",
companies:
[ "5b461c892bb9c81bd3ed4a25",
"5b5086196947782fbc873d28",
"5b76a6c79dc71a4a12564cc5" ]
}];
// your companies will be put in the folowing variable
var companies = [];
for ( var doc of docs){
for (var item of doc.companies){
companies.push(item)
}
}
console.log(companies)
const data = [ { _id: '5366e9049cfc825b32966852',
companies:
[ '5ab20bb69cb2754e949a09dc',
'5ac5d53983d45353bc6a9c54',
'5ac62eeca5421e4cb9abf63e']
},
{ _id: '5b9251f8ae8db624755f4b90',
companies:
[ '5b461c892bb9c81bd3ed4a25',
'5b5086196947782fbc873d28',
'5b76a6c79dc71a4a12564cc5' ]
}]
let outputArr = []
data.map(d => outputArr.push(d.companies));
//Flatten
console.log([].concat.apply([],outputArr))
Both flatMap and flat which are currently an 'experimental technology' will allow a cleaner approach to this problem in the future.
See:
Array.prototype.flat(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Array.prototype.flatMap(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
You want something like this:
var k = [{
_id: "5366e9049cfc825b32966852",
companies: ["5ab20bb69cb2754e949a09dc",
"5ac5d53983d45353bc6a9c54",
"5ac62eeca5421e4cb9abf63e"
]
},
{
_id: "5b9251f8ae8db624755f4b90",
companies: ["5b461c892bb9c81bd3ed4a25",
"5b5086196947782fbc873d28",
"5b76a6c79dc71a4a12564cc5"
]
}
];
var res = [];
k.forEach(function(id) {
res.push(...id.companies)
});
console.log(res);
jsonArray
[ { serial: '111',
certificateNumber: 'CCT1',
calibrationDate: '2018-01-02',
gaugeDescription: 'newR',
certificateName: '111.png',
email: 'chetde#dev.com',
dueDate: '2018-02-03'
},
{ serial: '222',
certificateNumber: 'CCT2',
calibrationDate: '2018-02-14',
gaugeDescription: 'newRR',
certificateName: '222.png',
email: 'chetaayade#devcom',
dueDate: '2018-01-16'
},
{ serial: '333',
certificateNumber: 'CCT3',
calibrationDate: '2018-01-08',
gaugeDescription: 'Records',
certificateName: '333.png',
email: 'chetan#dev.com',
dueDate: '2018-01-18' }
]
Uploded Docs
[ '333.png', '222.png' ]
how to filter by uploaded Docs
Try following (use filter)
var arr = [.....]; // your array
var uploadedDocs = [ '333.png', '222.png' ];
arr = arr.filter(function(item){
return uploadedDocs.indexOf(item.certificateName) !== -1;
});
Just use filter and includes
var uploadedDocs = [ '333.png', '222.png' ];
var output = jsonArray.filter( s => uploadedDocs.includes( s.certificateName ) );
Use filter(item) and indexOf() functions:
var uploadedDocs = [ '333.png', '222.png' ];
var filteredDocs = jsonArray.filter(item => item.indexOf(uploadedDocs) !== -1);
Is there anyway to convert this like the example below?
Convert this:
[
RowDataPacket { title: 'Code' },
RowDataPacket { title: 'Pizza' }
]
Into this:
['Code', 'Pizza']
I've provided you two possible solutions, in case if it's just an array of objects or an array of nested objects.
var arr = [{RowDataPacket: { title: 'Code' }}, {RowDataPacket: { title: 'Pizza' }}],
res = arr.map(v => v.RowDataPacket.title);
console.log(res);
var arr = [{ title: 'Code' }, { title: 'Pizza' }],
res = arr.map(v => v.title);
console.log(res);
Create a new array
var newArr = [];
And then push each item into the array
result.forEach(function(obj){
newArr.push(obj.title);
}
existing ["562fae5a626ca2e032947baa"]
new array [ { _id: '562fae5a626ca2e032947baa' },
{ _id: '562fae57626ca2e032947ba9' } ]
modified [ { _id: '562fae5a626ca2e032947baa' },
{ _id: '562fae57626ca2e032947ba9' } ]
I have an existing array and a new array, i want to compare the existing and the new array and remove the duplicates.
var existing = ["562fae5a626ca2e032947baa"];
var newArr = [ { _id: '562fae5a626ca2e032947baa' },
{ _id: '562fae57626ca2e032947ba9' } ];
newArr = newArr.filter(function(val){
return existing.indexOf(val) == -1;
});
console.log(newArr);
When i try to print newArr, i still get the two objects?
modified [ { _id: '562fae5a626ca2e032947baa' },
{ _id: '562fae57626ca2e032947ba9' } ]
I want the modified array to have only.
modified [{ _id: '562fae57626ca2e032947ba9' } ]
Below is the fiddle.
http://jsfiddle.net/ema6upg1/2/
newArr.filter(function(val){
return existing.indexOf(val._id) == -1;
})
is what you need, val is an object, you need to compare its _id
Your problem is, that one array contains objects.
var existing = ["562fae5a626ca2e032947baa"];
var newArr = [ { _id: '562fae5a626ca2e032947baa' },
{ _id: '562fae57626ca2e032947ba9' } ];
newArr = newArr.filter(function(val){
if(typeof val == "object") {
return existing.indexOf(val._id) == -1;
}
return existing.indexOf(val) == -1;
});
console.log(newArr);
The lookup for an object property is more efficient than iterating an array to find an id. Consider:
var existing = {
"562fae5a626ca2e032947baa": true
};
var newArr = [ { _id: '562fae5a626ca2e032947baa' },
{ _id: '562fae57626ca2e032947ba9' } ];
newArr.filter(function(val) {
return existing[val._id] || false;
}