Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract id from array using map with condition javascript

There is an 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.

like image 572
Hamid Shoja Avatar asked Mar 12 '20 11:03

Hamid Shoja


2 Answers

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)
like image 95
Eugen Sunic Avatar answered Oct 22 '22 22:10

Eugen Sunic


you can use a transducer in this case, so that you will not iterate through the array 2 times.

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 filteredIds = groups.reduce(
  (ids, { id, selected }) => (
    id > 0 && selected ? [...ids, id] : ids
  ), []
);

console.log(filteredIds);
like image 1
Yone Avatar answered Oct 22 '22 21:10

Yone