1

My use case: I have a two arrays one called "name" and the other called "customer". I need to extract the customers from the names list and get a new array called "lead".

const name = [{
  id: 1,
  name: "smith"
}, {
  id: 2,
  name: "john"
}]

const customer = [{
  id: 1,
  name: {
    id: 1,
    name: "smith"
  }
}]

I am expecting to get

lead = [{
  id: 2,
  name: "john"
}]

the code I am using is

const name = [{
  id: 1,
  name: "smith"
}, {
  id: 2,
  name: "john"
}]

const customer = [{
  id: 1 a,
  name: {
    id: 1,
    name: "smith"
  }
}]


const lead = name.filter(({
  id: id1
}) => !customer.some(({
  "name.id": id2
}) => id2 === id1));
console.log(lead);

This works if the data is flat, but when I use it with nested objects I get the full "name" list.

Working final code below

While Farrukh Normuradov answer does work, I used Pilchard's answer in the comments. I also fixed a typo.

Final code

const lead = name.filter(({ id: id1 }) => !customer.some(({ name: {id: id2} }) => id2 === id1));

5
  • 1
    Why are you expecting to get this object? Can you further clarify your selection criteria? Commented Feb 12, 2021 at 17:35
  • So, leads are names that are not customers? Commented Feb 12, 2021 at 17:37
  • I get a syntax error when I run your code, not the full "name" list. You have the right idea, using filter and !``some, I just think you have some syntax problems around "name.id". Commented Feb 12, 2021 at 17:42
  • your destructuring in your some() call is incorrect, it should be { name: {id: id2} } ( and the typo Mister JoJo mentioned) Commented Feb 12, 2021 at 17:46
  • @crawlings did my answer work for you? Commented Feb 12, 2021 at 18:00

1 Answer 1

2

I used filter, map and includes.

const user_list = [{
    id: 1,
    name: "smith"
}, {
    id: 2,
    name: "john"
},
{
    id: 3,
    name: "timur"
},
{
    id: 4,
    name: "igor"
},]

const customers = [{
    id: 1,
    name: {
        id: 1,
        name: "smith"
    }
},
{
    id: 4,
    name: {
        id: 4,
        name: "igor"
    }
}]

const leads = user_list.filter(user => !customers.map(customer => customer.id).includes(user.id))

console.log(leads);

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

1 Comment

The OP's use of some() is more efficient than map()ing the entire customers array as it will return as soon as it finds a match. The only problem with their code was their use of destructuring.

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.