Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

javascript - Filter array of objects with conditions

I want to filter an array like this:

const myArray = [
    { ageIndex: 4, nameIndex: 1, type: "group" },
    { ageIndex: 4, nameIndex: 0, type: "group" },
    { ageIndex: 5, nameIndex: 0, type: "person" },
    { ageIndex: 5, nameIndex: 1, type: "person" },
    { ageIndex: 5, type: "group" },
];

The new array should filter by unique ageIndex, but only when the type is group. The other objects of type person should stay unchanged. The nameIndex doesn't matter. There are group objects without a nameIndex.

const myNewArray = [
    { ageIndex: 4, nameIndex: 1, type: "group" },
    { ageIndex: 5, nameIndex: 0, type: "person" },
    { ageIndex: 5, nameIndex: 1, type: "person" },
    { ageIndex: 5, type: "group" },
];

How can I filter it like that?

question from:https://stackoverflow.com/questions/65898433/filter-array-of-objects-with-conditions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you ignore the nameIndex, i hope this could help:

const myArray = [
    { ageIndex: 4, nameIndex: 1, type: "group" },
    { ageIndex: 4, nameIndex: 0, type: "group" },
    { ageIndex: 5, nameIndex: 0, type: "person" },
    { ageIndex: 5, nameIndex: 1, type: "person" },
    { ageIndex: 5, type: "group" },
];

const filterSameGroup = arr => {
  const ageIndexes = [];
  return arr.filter(item => {
    if(item.type === "group") {
      if(ageIndexes.indexOf(item.ageIndex) != -1) {
        return false;
      }
      ageIndexes.push(item.ageIndex);
      return true;
    } 
    return true;
});
}

console.log(filterSameGroup(myArray));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...