I am trying to return an array that contain of one of property. So there is an array of objects like
[{x: 5, y: 607, width: 782, height: 602, line_width: 3, …},
{x: 10, y: 602, width: 772, height: 592, line_width: 3, …},
{x: 0, y: 400, size: 18, text: 'This cer..}, ..]
Some object has section: 'TextInstruction'
property defined and some do not.
I am trying to return an array that is only containing section
with no duplicate and no undefined.
So return ['TextInstruction', 'RectangleInstruction', ...]
No [undefined, 'TextInstruction', 'TextInstruction', ...]
Can anyone help me with JavaScript to get this using reduce() function?
CodePudding user response:
You don't need reduce to do that. You can do it with filter
and map
.
myArray
// filter missing sections
.filter(a => a.section)
// map to array of sections
.map(a => a.section)
// filter unique
.filter((a, i, arr) => arr.indexOf(a) === i)
CodePudding user response:
The reduce()
way of doing it could be something like this:
const data=[{a:12,b:45,section:"first"},{section:"second",d:5,f:7},{x:23,y:78,height:200},{a:445,x:34,section:"first"}];
const res1=Object.keys(data.reduce((a,c)=>{
if(c.section) a[c.section]=1;
return a;
}, {}));
// Or, using the es6 Set object:
const res2=[...data.reduce((a,c)=>{
if(c.section) a.add(c.section);
return a;
}, new Set())];
// show results:
console.log(res1,res2);
The second approach makes sense when the values to be collected are objects (and not only strings).
CodePudding user response:
You can try this:
var objectArray = {someting....}; // Your Object Array
var indexOfObject = objectArray.findIndex(object => {
return object.section == null;
});
objectArray.splice(indexOfObject, 1);