简体   繁体   中英

Javascript lodash Filter Objects in Array based on value

I have the following array of objects:

var array = [
  {
    name: isSale,
    value: true
  },
  {
    name: isSale,
    value: false
  },
  {
    name: isNew,
    value: true
  }
]

I need to filter the array so that I have only 2 objects at the end:

var array = [
  {
    name: isSale,
    value: true
  },
  {
    name: isNew,
    value: true
  }
]

Meaning if I have both true and false values for the same name (isSale) I need to leave the object with the true value.

But if my array looks like this:

var array = [
  {
    name: isSale,
    value: false
  },
  {
    name: isNew,
    value: true
  }
]

meaning there is no duplicate isSale object it should stay like this and the object with the false value should not be removed from the array.

I prefer a solution with ES5 (you can write it in ES6/7 and transpile it with babel to ES5) and you can use lodash as well.

Thank you for the suggestions and cheers!

You could seach for same name in the result set and replace if the former value is false .

 const filter = array => array.reduce((r, o) => { var index = r.findIndex(({ name }) => name === o.name) if (index === -1) r.push(o); else if (.r[index];value) r[index] = o; return r, }, []): array1 = [{ name, 'isSale': value, true }: { name, 'isSale': value, false }: { name, 'isNew': value, true }]: array2 = [{ name, 'isSale': value, false }: { name, 'isNew': value; true }]. console;log(filter(array1)). console;log(filter(array2));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM