-1

I have an array which has different location and items.

[
    {"location": "north", "items" : ["IT1", "IT2"]},
    {"location": "south", "items" : ["IT1", "IT2"]},
    {"location": "north", "items" : ["IT3", "IT4"]}
]

I want to remove duplicate location fields and append the items property from the duplicate to achieve this:

[
    {"location": "north", "items" : ["IT1", "IT2", "IT3", "IT4"]},
    {"location": "south", "items" : ["IT1", "IT2"]}
]

How can I do it with vanilla JS?

3 Answers 3

0

I hope it would work for you


var data = [
    {"location": "north", "items" : ["IT1", "IT2"]},
    {"location": "south", "items" : ["IT1", "IT2"]},
    {"location": "north", "items" : ["IT3", "IT4"]}
];

const result = data.filter((thing, index, self) =>
  index === self.findIndex((t) => (
    t.location === thing.location
  ))
)
console.log(result);

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

Comments

0

By adapting How to group or merge this array of objects in javascript? to accumulate arrays instead of numbers, here's the result:

var arr = [{
    "location": "north",
    "items": ["IT1", "IT2"]
  },
  {
    "location": "south",
    "items": ["IT1", "IT2"]
  },
  {
    "location": "north",
    "items": ["IT3", "IT4"]
  }
];

var finalArr = arr.reduce((m, o) => {
  var found = m.find(p => p.location === o.location);
  if (found) {
    found.items = found.items.concat(o.items);
  } else {
    m.push(o);
  }
  return m;
}, []);

console.log(finalArr)

Comments

0

Build an object with keys as location and values as aggregated items.

const process = (arr, track = {}) => {
  arr.forEach((obj) => {
    if (track[obj.location]) {
      track[obj.location] = {
        ...track[obj.location],
        items: obj.items.concat(track[obj.location].items),
      };
    } else {
      track[obj.location] = { ...obj };
    }
  });
  return Object.values(track);
};

const data = [
  { location: "north", items: ["IT1", "IT2"] },
  { location: "south", items: ["IT1", "IT2"] },
  { location: "north", items: ["IT3", "IT4"] },
];

console.log(process(data));

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.