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

228
Vistas
¿Cómo puedo ver si Object Array tiene un elemento en Another Object Array?

¿Hay alguna manera de saber si una matriz de objetos tiene elementos comunes a otra matriz de objetos y cuál es la intersección de ese objeto? (como una función Contiene). En el siguiente ejemplo, ProductId3 en Object Array 1, también está contenido en Object Array 2.

Estoy pensando en usar un bucle for doble. Sin embargo, ¿hay una forma más eficiente/óptima, o una función abreviada ecma o lodash?

 array1.forEach(arr1 => {
 array2.forEach(arr2 => { 
 if (arr1.productId === arr2.productId && 
 arr1.productName === arr2.productName ...

comprobando todos los miembros del objeto, no solo ProductId

Matriz de objetos 1:

 [
{
 ProductId: 50,
 ProductName: 'Test1',
 Location: 77,
 Supplier: 11,
 Quantity: 33
},
{
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
}
]

Matriz de objetos 2:

 [
{
 ProductId: 1,
 ProductName: 'ABC',
 Location: 3,
 Supplier: 4,
 Quantity: 52
},
{
 ProductId: 2,
 ProductName: 'DEF',
 Location: 1,
 Supplier: 2,
 Quantity: 87
},
{
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
},
{
 ProductId: 4,
 ProductName: 'XYZ',
 Location: 5,
 Supplier: 6,
 Quantity: 17
}
]
almost 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Para una solución simple pero razonablemente rápida, puede (1) usar un Set de productId de producto de la primera matriz, luego (2) filter la segunda matriz en función de las ID de la primera, solo tiene que revisar cada matriz una vez O(n) .

 let arr1 = [
 {
 ProductId: 50,
 ProductName: "Test1",
 Location: 77,
 Supplier: 11,
 Quantity: 33,
 },
 {
 ProductId: 3,
 ProductName: "GHI",
 Location: 1,
 Supplier: 4,
 Quantity: 25,
 },
];

let arr2 = [
 {
 ProductId: 1,
 ProductName: "ABC",
 Location: 3,
 Supplier: 4,
 Quantity: 52,
 },
 {
 ProductId: 2,
 ProductName: "DEF",
 Location: 1,
 Supplier: 2,
 Quantity: 87,
 },
 {
 ProductId: 3,
 ProductName: "GHI",
 Location: 1,
 Supplier: 4,
 Quantity: 25,
 },
 {
 ProductId: 4,
 ProductName: "XYZ",
 Location: 5,
 Supplier: 6,
 Quantity: 17,
 },
];

const getCommonItems = (arr1, arr2) => {
 let firstIdSet = new Set(arr1.map((product) => product.ProductId)); //1
 return arr2.filter((product) => firstIdSet.has(product.ProductId)); //2
};

console.log(getCommonItems(arr1, arr2));

almost 4 years ago · Santiago Trujillo Denunciar

0

¿Hay alguna manera de saber si una matriz de objetos tiene elementos comunes a otra matriz de objetos? - Sí, puedes lograr esto con la ayuda del método Array.some() . Devuelve verdadero si, en la matriz, encuentra un elemento para el cual la función proporcionada devuelve verdadero; de lo contrario, devuelve falso.

 const array1 = [{
 ProductId: 50,
 ProductName: 'Test1',
 Location: 77,
 Supplier: 11,
 Quantity: 33
}, {
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
}];

const array2 = [{
 ProductId: 1,
 ProductName: 'ABC',
 Location: 3,
 Supplier: 4,
 Quantity: 52
}, {
 ProductId: 2,
 ProductName: 'DEF',
 Location: 1,
 Supplier: 2,
 Quantity: 87
}, {
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
}, {
 ProductId: 4,
 ProductName: 'XYZ',
 Location: 5,
 Supplier: 6,
 Quantity: 17
}];

const isCommonProducts = array2.some(({ ProductId }) => array1.map(obj => obj.ProductId).includes(ProductId));

console.log(isCommonProducts);

Si desea obtener el objeto común, puede lograrlo con la ayuda del método Array.filter() .

 const array1 = [{
 ProductId: 50,
 ProductName: 'Test1',
 Location: 77,
 Supplier: 11,
 Quantity: 33
}, {
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
}];

const array2 = [{
 ProductId: 1,
 ProductName: 'ABC',
 Location: 3,
 Supplier: 4,
 Quantity: 52
}, {
 ProductId: 2,
 ProductName: 'DEF',
 Location: 1,
 Supplier: 2,
 Quantity: 87
}, {
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
}, {
 ProductId: 4,
 ProductName: 'XYZ',
 Location: 5,
 Supplier: 6,
 Quantity: 17
}];

const getFilteredProducts = array2.filter(({ ProductId }) => array1.map(obj => obj.ProductId).includes(ProductId));

console.log(getFilteredProducts);

almost 4 years ago · Santiago Trujillo Denunciar

0

Si podemos suponer que los elementos de cada matriz (los llamaremos sub-matrices ), que son matrices con claves, contienen exactamente las mismas claves en el mismo orden, entonces esta es mi idea:

  1. Convierta cada matriz en una matriz nueva cuyos elementos sean las representaciones JSON de los valores de la submatriz original. Esta es una operación o(N) realizada dos veces.
  2. De las nuevas matrices convertidas, encuentre la más corta. Convierte el otro en un conjunto. Esto también es o(N).
  3. Para cada elemento de la matriz convertida más corta, verifique si el conjunto contiene este valor. Esto también es o(N).

 let arr1 = [
{
 ProductId: 50,
 ProductName: 'Test1',
 Location: 77,
 Supplier: 11,
 Quantity: 33
},
{
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
}
];

let arr2 = [
{
 ProductId: 1,
 ProductName: 'ABC',
 Location: 3,
 Supplier: 4,
 Quantity: 52
},
{
 ProductId: 2,
 ProductName: 'DEF',
 Location: 1,
 Supplier: 2,
 Quantity: 87
},
{
 ProductId: 3,
 ProductName: 'GHI',
 Location: 1,
 Supplier: 4,
 Quantity: 25
},
{
 ProductId: 4,
 ProductName: 'XYZ',
 Location: 5,
 Supplier: 6,
 Quantity: 17
}
];

// Convert each sub-array's values to JSON string:
let arr1New = arr1.map(function(arr) {return JSON.stringify(Object.values(arr));});
let arr2New = arr2.map(function(arr) {return JSON.stringify(Object.values(arr));});

// Find shortest array of JSON strings:
const l1 = arr1New.length;
const l2 = arr2New.length;
// enumerate shortest list
let list, set, l, arr;
if (l1 <= l2) {
 list = arr1New;
 set = new Set(arr2New);
 l = l1;
 arr = arr1;
}
else {
 list = arr2New;
 set = new Set(arr1New);
 l = l2;
 arr = arr2;
}

for(let i = 0; i < l; i++) {
 if (set.has(list[i])) {
 console.log(arr[i]);
 }
}

almost 4 years ago · Santiago Trujillo 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