根据javascript / react中的属性过滤数组

时间:2017-06-20 11:45:24

标签: javascript arrays reactjs for-loop javascript-objects

您好我需要过滤具有相同地址的公司(数组)并创建一个类似的数组:

 [{address:uniqueaddress1,organization:[company1,company2]},
  {address:uniqueaddress2,organization:[company3,company4]
  .....]   

我使用以下代码:

 var organizations = [];
 var  dataPoints = [];
 for (var i = 0; i < companies.length; i++) {
  for (var j = 0; j < companies.length; j++) {
     if (i === j) continue;
     if (companies[j].address === companies[i].address) {
        organizations.push(companies[j]);            
        companies[j].added = true;  //To mark it is added
    }
    dataPoints.push({address:companies[j].address, organizations: companies[j]});
   }   
 }

原始阵列:

  0:Object
  added:true
  address:"sample address 1"
  id:258
  latitude:90.90227
  longitude:12.538208
  name:"Company name 1"
  postalCode:"90450"

2 个答案:

答案 0 :(得分:0)

您可以使用Map以更好的方式实现此目标(尽管您也可以将此方法用于已经完成的数组阵列)。您还可以使用更大的结果集删除内部循环以获得稍高的效率,只需添加,而不是为每个地址重新循环。

let original = [
    { address: '123 Example Street', id: 1 }, 
    { address: '123 Example Street', id: 2 },
    { address: '456 Example Street', id: 3 }
];

let grouped = new Map();

original.forEach(function(company) {

    let companies = grouped.get(company.address);

    // If we already have the key, then just push into the array.
    if (companies !== undefined) {
        companies.push(company);
    }
    else {
        // ...if not then create a new array.
        companies = [company];
    }

    grouped.set(company.address, companies);

});

答案 1 :(得分:0)

如果您习惯使用ES6语法,则可以使用filtermap方法执行此操作。下面的代码对数组comapanies进行过滤,map方法创建一个临时数组,然后我们使用indexOf方法检查我们是否可以在地图中包含相同的对象。

let companies = [{
  "added": true,
  "address": "sample address 1",
  "id": 258,
  "latitude": 90.90227,
  "longitude": 12.538208,
  "name": "Company name 1"
}, {
  "added": true,
  "address": "sample address 1",
  "id": 258,
  "latitude": 90.90227,
  "longitude": 12.538208,
  "name": "Company name 1"
}, {
  "added": true,
  "address": "sample address 2",
  "id": 258,
  "latitude": 90.90227,
  "longitude": 12.538208,
  "name": "Company name 1"
}, {
  "added": true,
  "address": "sample address 2",
  "id": 258,
  "latitude": 90.90227,
  "longitude": 12.538208,
  "name": "Company name 1"
}]

function uniqueArray(array, prop) {
  return array.filter((obj, pos, arr) => {
    return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
  });
}
console.log(uniqueArray(companies, "address"))

Credits