I have an array which looks like this
people = [ {id:1, name:"Bob", lang:English}, {id:2, name:"Sally", lang:German,Hebrew}, {id:3, name:"Trish", lang:English}, ]
I have a method to add to the array or to edit the existing array based on the input. This method has a new language which is given.I am adding a psuedocode.(Couldnt come up with anything better since I am very new to Typescript and Javascript).
onAddVariable() { //newLanguage is given to the input const people = people.map(person =>{ person.name === (new) //somehow to know if the name is a new name person.lang.push(newLanguage) return person } else{ people.push({id:4, name:newName, newLanguage}); return person } }
If a new person is given, then the output should look like.
people = [ {id:1, name:"Bob", lang:English}, {id:2, name:"Sally", lang:German,Hebrew}, {id:3, name:"Trish", lang:English}, {id:4, name:"Kash", lang:Urdu}, ]
If a new language is given to an existing person, then output should look like
people = [ {id:1, name:"Bob", lang:English,Spanish}, {id:2, name:"Sally", lang:German}, {id:3, name:"Trish", lang:English}, {id:4, name:"Kash", lang:Urdu}, ]
Advertisement
Answer
you can try something like this
basically addData returns a new array everytime so if you need to update the existing one you have to overwrite people
variable
the idea is that you are using the name as the field that you check for update or insert the record so first you create an object with name as key using reduce and in there you take care of your merge operations
Then you get rid of the keys using Object.values
and sort back the array based on keys
let people = [ {id:1, name:"Bob", lang:['English']}, {id:2, name:"Sally", lang:['German','Hebrew']}, {id:3, name:"Trish", lang:['English']}, ] const addData = (data, name, lang) => Object.values(data.reduce((res, {id, name, lang}) => { return { ...res, [name]: { ...(res[name] || {}), id, name, lang: [...new Set([...lang, ...(res[name] || {lang: []}).lang])] } } }, {[name]: {id: data.length + 1, name, lang: [lang]}})).sort((a, b) => a.id - b.id) console.log(addData(people, 'Yuri', 'Italian')) console.log(addData(people, 'Bob', 'Italian'))