Axxb 2020
Axxb 2020

Reputation: 15

how to filter an array when I use an array like geojson format

i have an array , and I want to filter the Array with BHID.

let array = [
{ 
 "type": "Feature",   
 "properties": 
        {
        "PID": 0, "SID": 2, "BHID": 1,
        }
},
{ 
 "type": "Feature",   
 "properties": 
        {
        "PID": 0, "SID": 8, "BHID": 2,
        },
},
{ 
 "type": "Feature",   
 "properties": 
        {
        "PID": 0, "SID": 5, "BHID": 1,
        },
}

]

and then I try to filter the array by BHID:

    for (let id = 0; id < maxId + 1; id++) {
      let entriesWithID = array.filter((entry) => {
        entry.properties.BHID === id;
      for (let i = 0; i < entriesWithID.length; i++) {
        console.log(entriesWithID[i]);
         }
      });

But I cannot get the correct result, what should I do to get the correct result.

Upvotes: 0

Views: 101

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28434

You can save the resulting entriesWithID at each iteration in an object as follows:

const array = [
  { 
    "type": "Feature",   
    "properties": { "PID": 0, "SID": 2, "BHID": 1 }
  },
  { 
    "type": "Feature",   
    "properties": { "PID": 0, "SID": 8, "BHID": 2 }
  },
  { 
    "type": "Feature",   
    "properties":  { "PID": 0, "SID": 5, "BHID": 1 }
  }
];
const maxId = 2;
const res = {};

for (let id = 0; id < maxId + 1; id++) {
  const entriesWithID = array.filter(entry => entry.properties.BHID === id);
  res[id] = entriesWithID;
}

console.log(res);

Another Approach:

Using Array#reduce, you can iterate over the array and group the items in an object by the BHID in the range you want. This will only store the categories found in the array with no empty ones:

const array = [
  { 
    "type": "Feature",   
    "properties": { "PID": 0, "SID": 2, "BHID": 1 }
  },
  { 
    "type": "Feature",   
    "properties": { "PID": 0, "SID": 8, "BHID": 2 }
  },
  { 
    "type": "Feature",   
    "properties":  { "PID": 0, "SID": 5, "BHID": 1 }
  }
];
const maxId = 2;

const res = array.reduce((acc, item) => {
  const bhId = item.properties.BHID;
  if(bhId >= 0 && bhId <= maxId) {
    acc[bhId] = [ ...(acc[bhId] || []), item ];
  }
  return acc;
}, {})

console.log(res);

Upvotes: 1

munanadi
munanadi

Reputation: 1079

You need to return the boolean condition check in the filter method.

The docs for this.

Change your code like this.

for (let id = 0; id < maxId + 1; id++) {
  let entriesWithID = array.filter((entry) => {
    return entry.properties.BHID === id;
  });

Upvotes: 0

Related Questions