1

I have two arrays,

array1 = [{name: "a", id: 1},{name: "b", id: 2},{name: "c", id: 3}]

and

array2 = [1, 2] // --which are the ids

I want to return a new array (array3) to display ["a", "b"] and if array2 = [1,3] then array3 should be ["a", "c"]

In other words, I would like to create a new array, with the names, corresponding to its id.

1
  • please add your try. Commented Apr 14, 2020 at 20:19

3 Answers 3

1

You can use reduce:

let a1 = [{name:'a', id:1},{name:'b', id:2},{name:'c', id:3}]
let a2 = [1,3]

let a3 = a1.reduce((carry, current) => {
    if (a2.includes(current.id)) {
        carry.push(current.name)
    }
    
    return carry
}, [])

alert(a3)

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

1 Comment

could you also tell me how to make the toaster notif stay longer , it only stays for 2 secs, i want it to stay longer
1

User filter to select the elements that meet your criteria, and map to get the property you want.

const array1 = [{name:"a", id:1},{name:"b", id:2},{name:"c", id:3}];
const array2=[1,2];
const array3 = array1.filter(i => array2.includes(i.id)).map(i => i.name);

array3 will contain ["a", "b"]

Comments

1

I would go ahead and perform the below:

for(int i = 0; i<array1.length(); ++i){
  for(int j = 0; j<array2.length(); ++j){
    if (array1[i].id==array2[j]){
      array3[j] = array[i].name;
    }
  }
}

Hope this is simple and it helps!

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.