Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Encuentra el elemento común con el índice más alto

Estoy tratando de refactorizar un fragmento de código en métodos menos detallados.

Básicamente tengo esta variedad de habilidades de usuario:

 const skills = ['add', 'edit', 'delete', 'secondSkill', 'fourthSkill']

Entonces tengo una serie de opciones de selección:

 const options = [ { label: "First", value: "firstSkill" }, { label: "Second", value: "secondSkill" }, { label: "Third", value: "thirdSkill" }, { label: "Fourth", value: "fourthSkill" } ];

Estoy tratando de escribir un método que:

  • encontrar los elementos comunes entre las habilidades y las opciones de los arreglos
  • devolver SOLAMENTE el elemento común con el índice más grande en la matriz de opciones

Por ejemplo: en este caso, quiero devolver la cuarta habilidad porque es el elemento con el índice más grande en mi matriz de opciones.

Se me ocurrió algo así:

 const findDefaultValue = (selectOptions, userSkills) => { const commonItems = selectOptions.filter((opt) => userSkills.includes(opt.value) ); const findIndexes = commonItems.map((item) => { return selectOptions.indexOf(item); }); const maxIndex = Math.max(...findIndexes); return options[maxIndex]; };

Funciona un poco, pero me gustaría saber de usted si hay formas más cortas de hacerlo. ¡Gracias!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Simplemente puede devolver el último elemento de commonItems , como:

 const findDefaultValue = (selectOptions, userSkills) => { const commonItems = selectOptions.filter((opt) => userSkills.includes(opt.value) ); return commonItems.at(-1); }

En el futuro, podrá usar findLast , como:

 const findDefaultValue = (selectOptions, userSkills) => { return selectOptions.findLast((opt) => userSkills.includes(opt.value) ); };
about 4 years ago · Juan Pablo Isaza Report

0

Dado que el índice particular no es importante, y todo lo que necesita es solo un elemento, puede iterar a través de una copia invertida de la matriz y devolver el primer elemento que coincida.

 const skills = ['add', 'edit', 'delete', 'secondSkill', 'fourthSkill'] const options = [{label: "First",value: "firstSkill"}, {label: "Second",value: "secondSkill"}, {label: "Third", value: "thirdSkill"}, {label: "Fourth",value: "fourthSkill"}]; const findDefaultValue = (selectOptions, userSkills) => { for(const {label, value} of [...selectOptions].reverse()) { if( userSkills.includes(value) ) { return {label,value}; } } return 'NONE FOUND'; }; console.log( findDefaultValue(options, skills) ); /*OUTPUT: { "label": "Fourth", "value": "fourthSkill" } */

Alternativamente, puede usar el one-liner de @AlexandrBelan con la advertencia de usar una copia, por lo que las options permanecen sin cambios:

 const skills = ['add', 'edit', 'delete', 'secondSkill', 'fourthSkill'] const options = [{label: "First",value: "firstSkill"}, {label: "Second",value: "secondSkill"}, {label: "Third", value: "thirdSkill"}, {label: "Fourth",value: "fourthSkill"}]; const findDefaultValue = (selectOptions, userSkills) => [...selectOptions].reverse().find(({value}) => userSkills.includes(value)); console.log( findDefaultValue(options, skills) ); /*OUTPUT: { "label": "Fourth", "value": "fourthSkill" } */

about 4 years ago · Juan Pablo Isaza Report

0

Otra solución. De una sola línea si no te importa.

 const skills = ['add', 'edit', 'delete', 'secondSkill', 'fourthSkill'] const options = [{label: "First",value: "firstSkill"}, {label: "Second",value: "secondSkill"}, {label: "Third", value: "thirdSkill"}, {label: "Fourth",value: "fourthSkill"}]; const result = options.reverse().find(({ value }) => skills.includes(value)); console.log(result);
 .as-console-wrapper{min-height: 100%!important; top: 0}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!