Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

552
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda