简体   繁体   中英

JS - Check if element exist in loop

I try to loop inside a array, check if element is not null and ignore duplicates. Looks similar to

let tempArr = [];
ARRAY.forEach(element => {
  if(element['sf'] !=null){
    if(tempArr.find(test => test.descripcion != element['sf'])){
    tempArr.push({
    id: element['id'], descripcion: element['sf'] });   
  }

But something fails, return empty array.

Somebody know how can i ignore duplicates elements in foreach loop?

You can use reduce and every for this:

 const arr = [ { id: 0, sf: 'a' }, // ok { id: 1, sf: null }, // <- no { id: 2, sf: 'b' }, // ok { id: 3, sf: 'c' }, // ok { id: 4, sf: 'c' }, // <- no { id: 5, sf: 'd' } // ok ]; const result = arr.reduce((res, el) => { if (el.sf !== null && res.every(x => x.descripcion !== el.sf)) { return res.concat({ id: el.id, descripcion: el.sf }); } return res; }, []); console.log(result);

Instead of iterating your result each time, you can use an intermediate set to keep track of what was inserted, and then use a simple Array.filter()

 const ARRAY = [ { id: 1, sf: null }, { id: 2, sf: 'foo' }, { id: 3, sf: 'bar' }, { id: 4, sf: 'foo' } ]; const result = function(data) { const seen = new Set() return data.filter(item => { if (item.sf === null || seen.has(item.sf)) { return false; } seen.add(item.sf) return true; }) }(ARRAY); console.log(result);

Alternatively, to combine filter and map operation, you could use Array.reduce ; the logic that you're after can be generalised to an extent, like so:

// reusable function to filter and map at the same time
function filterMap(array, fn) {
  return array.reduce((acc, o) => {
    const data = fn(o)
    if (data === undefined) {
      return acc; // map function didn't return anything
    }
    acc.push(data);
    return acc;
  }, []);
}

const result = function(data) {
  const seen = new Set()
  return filterMap(data, item => {
    if (item.sf === null || seen.has(item.sf)) {
      return;
    }
    seen.add(item.sf);
    return {id: item.id, sf: item.sf};
  });
}(ARRAY);

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