0

I have an array of objects:

const obj = [
        { name: 'Test', age: 25 },
        { name: 'App', age: 27 },
        { name: 'Const', age: 28 },
];

and I have the other one:

const value = [
        { surname: 'Test', age: 54 },
        { surname: 'Back', age: 54 },
        { surname: 'Front', age: 54 },
        { surname: 'Const', age: 54 },
        { surname: 'App', age: 54 },
];

Now, I want to leave in the second array only objects, which have name === surname and the other ones delete. Keys must be different, but the values in them must be the same. For example: {name: "Test", age: 25} === {surname: "Test", age: 54}(it's just an example) How to make it?

4 Answers 4

1

Try this

const obj = [
  { name: 'Test', age: 25 },
  { name: 'App', age: 27 },
  { name: 'Const', age: 28 },
];

let value = [
  { surname: 'Test', age: 54 },
  { surname: 'Back', age: 54 },
  { surname: 'Front', age: 54 },
  { surname: 'Const', age: 54 },
  { surname: 'App', age: 54 },
];

const names = obj.map(el => el.name);

value = value.filter(el => names.includes(el.surname));

or like this:

const obj = [
  { name: 'Test', age: 25 },
  { name: 'App', age: 27 },
  { name: 'Const', age: 28 },
];

const names = obj.map(el => el.name);

const value = [
  { surname: 'Test', age: 54 },
  { surname: 'Back', age: 54 },
  { surname: 'Front', age: 54 },
  { surname: 'Const', age: 54 },
  { surname: 'App', age: 54 },
].filter(el => names.includes(el.surname));
Sign up to request clarification or add additional context in comments.

Comments

1

Use filter and some:

const myArrayFiltered = obj.filter( el => {
  return value.some( f => {
    return f.surname === el.name;
  });
});

Comments

1

Your have to use filter and see if there is a key in the second list.
And don't forget to reassign the result of filter() to the value list as the filter doesn't change the original list, but returns a new, filtered one.

value = value.filter(oneVal => obj.find(o => o.name === oneVal.surname))

More on filter() here

Comments

1

Use embedded Javascript's find and filter methods:

value.filter(k => 
   obj.find(v => v.name === k.surname)
)

This basically says "filter all values from value array that match this criteria". And the criteria is "find values in obj where name equals surname".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.