Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

72
Visualizações
Add or edit the typescript array based on the condition which is given

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},
        ]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you could simply add check and try something like this in your function

let people = [
      {id:1, name:"Bob", lang:["English"]},
      {id:2, name:"Sally", lang:["German","Hebrew"]},
      {id:3, name:"Trish", lang:["English"]},
    ]
let name1="Boby"
let langnew="french"
let newname=true;
people.forEach((p)=>{
    if(p.name===name1){
        newname=false;
        if(!p.lang.includes(langnew)){
            p.lang.push(langnew)
        }
    }
})
if(newname===true){
    let ar=[]
    ar.push(langnew);
    people.push({ id:people.length+1 ,name:name1,lang:ar})
}
console.log("array",people)

about 4 years ago · Juan Pablo Isaza Relatório

0

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'))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda