I have an array of objects in javascript like:
var arr_objects= [
{id: 1, authors: "person1||person2", edithors: "person1||person7"},
{id: 2, authors: "person3", edithors: "person2"},
{id: 3, authors: "person4||person5||person6", edithors: "person7||person6"},
{id: 4, authors: "person7||person6", edithors: "person6"}
];
I want to check if any name in "authors" (person1, person2 etc.) occurs in the same object in "edithors". If thats the case - write a new key-value pair ("occurance") to the object containing the name of the author/editor.
The output should look like this:
var arr_objects= [
{id: 1, authors: "person1||person2", edithors: "person1||person7", occurance: "person1"},
{id: 2, authors: "person3", editors: "person2" },
{id: 3, authors: "person4||person5||person6", edithors: "person7||person6", occurance: "person6"},
{id: 4, authors: "person7||person6", edithors: "person6", occurance: "person6"}
];
I am new to programming and seem to be completely stuck. I guess to achieve the output, I have to use regulair expressions on "authors" and "editors" to separate the values and compaire both strings with eachoter. Unfortunately am unable to use the regex and loop through the array while comparing the values.
I would be very thankful for any advice regarding my problem.
Here is a solution with some explanations
arr_objects.map(function(item)
{
// split both authors and editors into an array
let authors = item.authors.split('||');
let editors = item.edithors.split('||');
let occurance = [];
// for each author, check if it also appears among editors
for (a in authors)
{
if (editors.indexOf(authors[a])>=0)
{
//if yes, push it into occurrence buffer
occurance.push(authors[a]);
}
}
// join the array into a string
item.occurance = occurance.join('||');
return item;
})