extract id from array using map with condition javascript

Hamid Shoja :

There is a array of objects

  const groups = [
    { id: 0, name: "All", selected: false },
    { id: -1, name: "All", selected: true },
    { id: 1, name: "Group1", selected: false },
    { id: 2, name: "Group2", selected: false },
    { id: 3, name: "Group3", selected: false },
    { id: 4, name: "Group4", selected: true }
  ];

I want to extract ids from this object with map

groups.map(group => group.id > 0 && group.selected ? group.id:null)

but the result will be [null,null,4,null...] actually it should be [4]

I know I can use another function like forEach and push or map and filter but I would solve it with one iteration with map or something else.

Eugen Sunic :

Filter the object/s under your criteria and then extract the id/s with a map

const groups = [{
    id: 0,
    name: "All",
    selected: false
  },
  {
    id: -1,
    name: "All",
    selected: true
  },
  {
    id: 1,
    name: "Group1",
    selected: false
  },
  {
    id: 2,
    name: "Group2",
    selected: false
  },
  {
    id: 3,
    name: "Group3",
    selected: false
  },
  {
    id: 4,
    name: "Group4",
    selected: true
  }
];


const result = groups.filter(x => x.id > 0 && x.selected).map(x => x.id)
console.log(result)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302208&siteId=1