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

553
Visualizações
How to swap key-value and only return the first pair in javascript?
  1. Here is the task
  • @param {object} ???
  • @returns {object} an object with the given object's values as keys, and keys as values. If there are duplicate values in the input object, only the first key-value pair should be used and subsequent pairs with the same value discarded.

2.Here is what i did code

What's wrong with it? How should i rework?

const object5 = { a: 1, b: 2, c: 3, d: 1 };
const object6 = { a: 1, b: 1, c: 1, d: 1 };

function swapPairs2(obj){                                    
    let newObject = {};
    for(const key in obj){
        let value = obj[key]
        newObject[value] = key;
    }
    return newObject;
} 

3.Here are the tests

test(swapPairs2(object5), { 1: "a", 2: "b", 3: "c" });
test(swapPairs2(object6), { 1: "a" });

4.Here is the error i got

I am supposed to get the first key-value pair, but a random return.

enter image description here

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can also reverse the entries.

const object5 = { a: 1, b: 2, c: 3, d: 1 };
const object6 = { a: 1, b: 1, c: 1, d: 1 };
const swapPairs2 = obj => Object.fromEntries(
  Object.entries(obj)
    .reverse() // Keep the first, not the last
    .map(entry => [entry[1], entry[0]]) // Reverse the key and vlaue
);
console.log(swapPairs2(object5));
console.log(swapPairs2(object6));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it by taking the object keys and using the Array.reduce() method on the keys.

const object5 = { a: 1, b: 2, c: 3, d: 1 };
const object6 = { a: 1, b: 1, c: 1, d: 1 };

const swapPairs2 = (obj) => Object.keys(obj)
  .reduce((a, c) => (a[obj[c]] = a[obj[c]] ?? c, a), {});

console.log(swapPairs2(object5));
console.log(swapPairs2(object6));

Or using the Array.reduce() method on the Object.entries()

const object5 = { a: 1, b: 2, c: 3, d: 1 };
const object6 = { a: 1, b: 1, c: 1, d: 1 };

const swapPairs2 = obj => Object.entries(obj)
    .reduce((acc, [key, val]) => (acc[val] = acc[val] ?? key, acc), {})

console.log(swapPairs2(object5));
console.log(swapPairs2(object6));

about 4 years ago · Juan Pablo Isaza Relatório

0

Only add the value/key pairs, if the value doesn't already exist on newObject by checking with the in operator:

function swapPairs2(obj) {
  const newObject = {};
  for (const key in obj) {
    const value = obj[key];
    if(!(value in newObject)) {
      newObject[value] = key;
    }
  }
  return newObject;
}

const object5 = { a: 1, b: 2, c: 3, d: 1 };
const object6 = { a: 1, b: 1, c: 1, d: 1 };

console.log(swapPairs2(object5));
console.log(swapPairs2(object6));

Another option is to use Array.reduce():

const swapPairs2 = obj =>
  Object.entries(obj)
    .reduce((acc, [k, v]) => 
      v in acc 
      ? acc
      : { ...acc, [v]: k }
    , {})

const object5 = { a: 1, b: 2, c: 3, d: 1 };
const object6 = { a: 1, b: 1, c: 1, d: 1 };

console.log(swapPairs2(object5));
console.log(swapPairs2(object6));

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