0

I'm trying to create an array from two other arrays using a loop, where in both arrays I compare two strings and when I find two strings that are the same I push the value to the array from second compared array, and if I don't find it I push 0. The problem is that the array has to be exactly the length of the first array.

const array1 = ['21', '22', '23', '24', '25', '26', '27'] const array2 = [{score: 1, date: '21'}, {score: 3, date: '23'} ] 

output should look like this: [1, 0, 3, 0, 0, 0, 0] <=== this array must have length of array1, and i have problem to create proper loop, or maybe this is shouldnt be loop?

1
  • Welcome to Stack Overflow! You are encouraged to make an attempt to write your code. If you encounter a specific technical problem during that attempt, such as an error or unexpected result, we can help with that. Please provide specific information about that attempt and what didn't work as expected. To learn more about this community and how we can help you, please start with the tour and read How to Ask and its linked resources. Commented Mar 26, 2022 at 11:02

1 Answer 1

3

You can achieve this by combining map() (to iterate over the first array) and find() (to get the right score out of the second array). To fall back to 0 in case there is no result in array2, you can combine optional chaining with nullish coalescing.

const array1 = ['21', '22', '23', '24', '25', '26', '27']; const array2 = [{score: 1, date: '21'}, {score: 3, date: '23'} ]; const array3 = array1.map(value => array2.find(obj => obj.date === value)?.score ?? 0); console.log(array3);

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

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.