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?

1

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.