1

hello i want to know how can i achieve this approach: i have this array of objects:

const array =[{district:1,buildings:["1","2"]},{district:1,buildings:["1","3"]},{district:2,buildings:["1","2"]}]

i want to merge the objects of the array + merging the buildings of the object with same district.

what should i get :

const array =[{district:1,buildings:["1","2","3"]},{district:2,buildings:["1","2"]}]

any help. thanks

note: this is can be done with for loop but i am looking for simpler approach.

4 Answers 4

2

This is a solution, which:

  • does not overwrite / change the original array
  • is fully functional

Explanation:

  1. Use array.reduce(..) to reduce the list to only two unique entries (district 1 and 2) that has a (possibly) non-unique list of buildings each.
  2. Use Object.entries(..).map(..) to be able to iterate the districts in order to make the buildings property unique.

 const array = [
  { district: 1, buildings: [ '1', '2' ] },
  { district: 1, buildings: [ '1', '3' ] },
  { district: 2, buildings: [ '1', '2' ] }
];
 
 const result = Object.entries(
  array.reduce(
    (acc, {district, buildings}) => {
        acc[district] = acc[district] ? acc[district] : []; 
        acc[district].push(...buildings);
        return acc;
    }, 
    []
  )
).map(m => ({district: parseInt(m[0]), buildings: [...new Set(m[1])]}));

console.log(result);

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

Comments

1

You can use Array.prototype.reduce to create an object which will store all values for a particular district(district will be keys)

After this, you will have an object with keys as districts and value as building array. Then you can recreate an array using an Array.prototype.map and set to remove duplicates.

const array = [{
    district: 1,
    buildings: ["1", "2"]
  },
  {
    district: 1,
    buildings: ["1", "3"]
  },
  {
    district: 2,
    buildings: ["1", "2"]
  }
];

let mapped_array = array.reduce((acc, val) => {
  acc[val.district] = acc[val.district] ?
    acc[val.district].concat(val.buildings) :
    val.buildings;
  return acc;
}, {});

mapped_array = Object.keys(mapped_array).map(val => {
  return {
    district: val,
    buildings: [...new Set(mapped_array[val])]
  };
});

console.log(mapped_array);

Comments

0

You can do it like this:

const array = [{district:1,buildings:["1","2"]},{district:1,buildings:["1","3"]},{district:2,buildings:["1","2"]}];

function merge(arr){

  let result = [];
  
   arr.forEach(item => {
    if(result[item.district]){
       item.buildings.forEach(val => {result[item.district].add(val)});
    } else {
       result[item.district] = new Set(item.buildings);
    }
  })
  
  return result.filter(item => item).map((item,i) => {return {district: i + 1, buidings: [...item]}});

}

console.log(merge(array));

1 Comment

good one! but i am still looking for simpler method. anyway thank you!
0

Loops are good, however here's an approach using a few built in methods:

const array =[{district:1,buildings:["1","2"]},{district:1,buildings:["1","3"]},{district:2,buildings:["1","2"]}]

var result = {}; //will store our results, object/dict used for optimal indexing
array.map(function(row){ //for each row in the array
    //if we have no existing record of it, we will store that record
   if(!result[row.district])result[row.district]=row;
   else{
      //since we have an existing record we will modify it
      //for each building num in the new record
      row["buildings"].map(function(buildingNum){
            //if the building number doesn't exist in the existing record
           if(result[row.district]['buildings'].indexOf(buildingNum)==-1){
               result[row.district]['buildings'].push(buildingNum) //add it
           }
      })

   }
})
result=Object.values(result) //convert our result back to an array

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.