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:
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!
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) ); };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" } */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}