2

I have created one example for you to understand the problem.

let arr = [];
arr.push({
  module_id: 41,
  name: 'first'
}, {
  module_id: 41,
  name: 'second',
  important: true,
}, {
  module_id: 43,
  name: 'third'
});

const lookup = arr.reduce((a, e) => {
  a[e.module_id] = ++a[e.module_id] || 0;
  return a;
}, {});
console.log('lookup is', lookup);

let unique = [];
arr.filter((e) => {

  if (lookup[e.module_id] === 0) {
    unique.push(e)
  }
})

console.log('unique', unique)

first, I have an empty array arr and I am pushing 3 objects in it.
Notice, the module_name. There are two repeatings and I'd like to use the second one with the property name important.
I have used reduce here for finding out which one is repeating based on module_name. it'll return 1 with the key of 41 and 0 for 43. I want to use both but I don't want to duplicate into my unique array. Currently, I'll push only those elements which are unique, in our case module_id: 43.
Now how can I get the duplicate value (with important property)?

1

4 Answers 4

3

let arr = [];
arr.push(
  {
    module_id: 41,
    name: 'first',
  },
  {
    module_id: 41,
    name: 'second',
    important: true,
  },
  {
    module_id: 43,
    name: 'third',
  }
);


const result = arr.reduce(
  (acc, curr) =>
    acc.find((v) => v.module_id === curr.module_id) ? acc : [...acc, curr],
  []
);

console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

this does not return the object with important property.
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
1

You could take a Map and get only distinct first values or the ones with important flag.

const
    array = [{ module_id: 41, name: 'first' }, { module_id: 41, name: 'second', important: true }, { module_id: 43, name: 'third' }],
    result = Array.from(array
        .reduce(
            (m, o) => m.set(o.module_id, !o.important && m.get(o.module_id) || o),
            new Map
        )
        .values()
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

1

try

let unique = [];
arr.filter((e) => {

  if (lookup[e.module_id] === 0) {
    unique.push(e)
  }
  else if (e.important) {
    unique.push(e)
  }
})

Comments

0
const arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5];
const uniqueNums = arr.reduce( (all,item) => {
  if(all.indexOf(item) === -1) {
    all.push(item)
  }
  return all
},[])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.