Skip to content

Instantly share code, notes, and snippets.

@ricardroberg
Last active August 2, 2022 20:24
Show Gist options
  • Save ricardroberg/c696f1bd14bd575ea082579621ad2352 to your computer and use it in GitHub Desktop.
Save ricardroberg/c696f1bd14bd575ea082579621ad2352 to your computer and use it in GitHub Desktop.
Put two arrays togeter and create tow object for each element´s array not present
export function CheckColumns(expected, given) {
const valid = expected.reduce(
(state, curr) => {
if (given.includes(curr)) {
state.validWithMatch.push([curr, curr])
} else {
state.validWithoutMatch.push(curr)
}
return state
},
{ validWithMatch: [], validWithoutMatch: [] }
)
const invalid = given.reduce(
(state, curr) => {
if (!expected.includes(curr)) state.refuse.push(curr)
return state
},
{ refuse: [] }
)
const outCasts = (validWithoutMatch, refuse) => {
const eventOutput = Array.from(Array(Math.max(validWithoutMatch.length, refuse.length)), (_, index) => [
validWithoutMatch[index] || '',
refuse[index] || ''
])
return eventOutput
}
const finalArray = outCasts(valid.validWithoutMatch, invalid.refuse)
.sort((a, b) => {
if (a.includes('') || b.includes('')) return -1
})
.concat(valid.validWithMatch)
return { finalArray }
}
@ricardroberg
Copy link
Author

ricardroberg commented Aug 2, 2022

Recebe dois arrays. Caso haja o mesmo elemento em ambas então é adicionada a chave validWithMatch, caso só hava o valo no primeiro array então vai para a chave validWitoutMatch, e todos os elementos que existem apenas no segundo array vão para a chave refuse

Depois é feito um "ZIP" dos arrays que não possuem correspondência (validWithoutMatch e refuse) e o que sobrar fica relacionada a uma string vazia ''.

Formato:
[string || '', string || '']

Ordem:

  1. Arrays com strings vazia em um dos campos
  2. Arrays não relacionadas
  3. Arrays com valores iguais

OBS: Não são considerados valores duplicados.

Exemplo de saída:

{
  finalArray: [
    [ '', 'maisum' ],
    [ '', 'sobrei' ],
    [ 'quatro', 'pera' ],
    [ 'sete', 'uva' ],
    [ 'oito', 'abacaxi' ],
    [ 'um', 'um' ],
    [ 'dois', 'dois' ],
    [ 'tres', 'tres' ],
    [ 'cinco', 'cinco' ],
    [ 'seis', 'seis' ],
    [ 'nove', 'nove' ],
    [ 'dez', 'dez' ]
  ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment