0

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
see
  • 61
  • 4
  • Why do you want to use `reduce`? Seems like you want to filter the objects that do not have a `section` key. Also, the intended result is unclear; it looks like what you want is an array of the unique values of the `section` key, which you could do easily with the answers to [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) and [Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array](https://stackoverflow.com/q/840781/215552) – Heretic Monkey Oct 07 '22 at 17:34

3 Answers3

0

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)
Clem
  • 2,150
  • 15
  • 17
0

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).

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

You can try this:

var objectArray = {someting....}; // Your Object Array
var indexOfObject = objectArray.findIndex(object => {
    return object.section == null;
});
objectArray.splice(indexOfObject, 1);
Hamid Raza
  • 28
  • 1
  • 6