0

I need inner join with two array in javascript like this:

    
    array1 = 
    [
      {
        "id": 1,
        "name": "Tufan"
      },
      {
        "id": 2,
        "name": "Batuhan"
      },
      {
        "id": 3,
        "name": "Hasan"
      }
    ]
    
    array2 = 
    [
      {
        "name": "yyy",
        "externalid": "1",
        "value": "Asd"
      },
      {
        "name": "aaaa"
        "externalid": "2",
        "value": "ttt"
      }
    ]
    
    expectedArray = 
    [
      {
        "id": 1,
        "name": "Tufan",
        "externalid": "1",
        "value": "Asd"
      },
      {
        "id": 2,
        "name": "Batuhan",
        "externalid": "2",
        "value": "ttt"
      }
    ]

rules:

  1. on: array2.externalid = array1.id
  2. select: array1.id, array1.name, array2.externalid, array2.value

My approach:

array1.filter(e => array2.some(f => f.externalid == e.id));
// I need help for continue

How can I make this?

Doesn't matter information: I use ES5 and pure javascript

4

1 Answer 1

1

You can do it like this:

const res = array2.map((item) => {
  const related = array1.find((el) => el.id == item.externalid);
  return { ...item, ...related };
});

Using a map to loop over the array2 and a find to get the array1 relative.

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

2 Comments

... operator not supported es5 :(
@TufyDuck what browsers are your building this for? Why don't you use Babel if you're concerned?

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.