0

I have this Data Structure :

const data = [

{ id: 1, urlName: 'balance-at-work', offices: [ { location: 'Sydney, Australia', in_range: false }, ], }, { id: 2, urlName: 'spring-development', offices: [ { location: 'Banbury, Oxfordshire', in_range: true }, ], }, { id: 3, urlName: 'talent-lab', offices: [ { location: 'México City, Mexico', in_range: false }, { location: 'London, UK', in_range: true }, ], }, ];

I want to reduce the offices array inside each object by using the great circle distance formula.

So far i have been able to calculate the great circle distance and add a dist key inside each office object. What i am having issue with, is a clean way to remove all the objects inside each offices array for each user when dist is greater than a given range.

3
  • 1
    And the problem is? Array.prototype.filter(), a simple for loop (iterate from the last to the first item) + .splice(), ... Commented Jun 1, 2021 at 12:26
  • Please give an example of input is this and output should be this. Its hard to comprehend the problem. Commented Jun 1, 2021 at 12:48
  • yes @ShravanDhar the output is the same but if the office didn't match the range than i should remove it. If the office array is empty then the whole parent object should be removed. Commented Jun 1, 2021 at 13:03

1 Answer 1

1

A simple way to do this might be something like the following (is_office_in_range is just a placeholder for however you determine whether an office should be included or not):

const data = [
  {
    id: 1,
    urlName: 'balance-at-work',
    offices: [
      {
        location: 'Sydney, Australia',
      },
    ],
  },
  {
    id: 2,
    urlName: 'spring-development',
    offices: [
      {
        location: 'Banbury, Oxfordshire, UK',
      },
    ],
  },
  {
    id: 3,
    urlName: 'talent-lab',
    offices: [
      {
        location: 'México City, Mexico',
      },
      {
        location: 'London, UK',
      },
    ],
  },
];

const is_office_in_range = (office) => office.location.endsWith('UK');

const res = data
  .map((company) => ({
    ...company,
    offices: company.offices.filter((office) => is_office_in_range(office))
  }))
  .filter((company) => company.offices.length);

console.log(res);

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please share with me the way to insert in_range field ? is there a way to do it without nested loops ?
@AnthonyG.Helou You wouldn't necessarily need to insert the in_range field; in the office filter you could replace office.in_range with a function call to check whether the office is in range e.g. is_office_in_range(office).

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.