1

suppose i have two arrays like below =>

const arr1 = {
 books: ["a1","a2"],
 categories: ["c1", "c2"]
}

const arr2 = [
{
"books": [{
 label: "a1",
  count: 2
},
{
 label: "a3",
  count: 4
}],

"categories": [{
 label: "c2",
  count: 2
},
{
 label: "c3",
  count: 4
}]
}]

How can i check if all the books in arr1 which is array of strings exist in arr2[0].books which is array of objects? If it doesnt exist then i want to create an object in arr2[0].books with {label: "whatever string doesn't exist in arr2", count: 0}. I want to do it for each arr2 objects books and categories

I tried below code: -

arr1.books.map(i => {
   return arr2[0].books.find(item => i == item.label);
});

Expected Result -

arr2 = [
{
"books": [{
 label: "a1",
  count: 2
},
{
 label: "a3",
  count: 4
}, {
 label: "a2",
  count: 0
}

],

"categories": [{
 label: "c2",
  count: 2
},
{
 label: "c3",
  count: 4
},{
 label: "c1",
  count: 0
}]
}]

which is label: a2 is added to books in arr2 as it didnt exist, and similarly c1 in arr2 of categories . and sort based on count desc

2
  • is arr1 an array? or object? Commented May 5, 2022 at 7:49
  • object whose properties are arr of strings "books" & "categories" Commented May 5, 2022 at 7:51

2 Answers 2

1

You can do:

const arr1 = { books: ['a1', 'a2'], categories: ['c1', 'c2'] }
const arr2 = [
  {
    books: [{ label: 'a1', count: 2 }, { label: 'a3', count: 4 }],
    categories: [{ label: 'c2', count: 2 }, { label: 'c3', count: 4 }]
  }
]

arr2.forEach(obj => Object.keys(obj).forEach(key => arr1[key]
  .filter(name => !obj[key].some(({ label }) => label === name))
  .forEach(name => obj[key].push({ label: name, count: 0 }))
))

console.log(arr2)

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

1 Comment

this gives incorrect results for "categories", if you check it has 2 objects with "c2"
0

you can do this

const arr1 = {
 books: ["a1","a2"],
 categories: ["c1", "c2"]
}

const arr2 = [
{
"books": [{
 label: "a1",
  count: 2
},
{
 label: "a3",
  count: 4
}],

"categories": [{
 label: "c2",
  count: 2
},
{
 label: "c3",
  count: 4
}]
}]

const arr3 = Object.fromEntries(Object.entries(arr1).map(([key, value]) => [
 key,
 value.map(v => arr2[0][key].find(({label}) => label === v) || {label: v, count: 0})
] ))
console.log(arr3)

2 Comments

I think you're missing the a3 and c3
thx but its missing elements a3 and c3

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.