Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
¿Cómo verificar si una matriz de matriz contiene al menos un elemento?

Estoy enfrentando un problema en el filtro de javascript.

Supongamos que esto es una array1 -

 const array1 = [ { title: 'Stock market news', symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'], }, { title: 'Neil Young urges Spotify', symbols: ['SPOT.US', '639.F', '639.XETRA'] }, { title: 'Neil Young urges Spotify', symbols: ['AAPl.US', '639.F', '639.XETRA'] } ]

Y esto es una array2

 const array2 = [ {Code: "AAPL"}, {Code: 'SPOT'} ]

Tengo que archivar array1 y eliminar un objeto que no completa la condición. La condición es si los símbolos de array1 contienen al menos un elemento de Code de array2. Quiero decir, si el Code array2 coincide con el campo de símbolos arry1 al menos un elemento.

En el ejemplo anterior, el resultado debería ser:

 const array1 = [ { title: 'Neil Young urges Spotify', symbols: ['SPOT.US', '639.F', '639.XETRA'] }, { title: 'Neil Young urges Spotify', symbols: ['AAPl.US', '639.F', '639.XETRA'] } ]

Porque estos dos objetos contienen AAPL y SPOT en el campo de símbolos. Creo que puedo aclarar todas las cosas.

Estoy tratando de esta manera-

 const filterData = array1.filter(function (array1El) { return !array2.find(function (array2El) { return array1El.symbols.includes(`${array2El.Code}.US`); }) });

Pero no está funcionando. Por favor, dime dónde me equivoco.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Hay dos problemas:

  • Su condición !array2.find está al revés: desea filtrar para incluir elementos para los que array2.find tiene una coincidencia, no elementos para los que no la tiene.
  • 'AAPl.US' !== 'AAPL.US' - hágalos en el mismo caso antes de comparar.

También sería más claro usar .some en lugar de .find .

 const array1 = [ { title: 'Stock market news', symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'], }, { title: 'Neil Young urges Spotify', symbols: ['SPOT.US', '639.F', '639.XETRA'] }, { title: 'Neil Young urges Spotify', symbols: ['AAPl.US', '639.F', '639.XETRA'] } ] const array2 = [ {Code: "AAPL"}, {Code: 'SPOT'} ] const filterData = array1.filter(function (array1El) { return array2.some(function (array2El) { return array1El.symbols .map(s => s.toLowerCase()) .includes(`${array2El.Code.toLowerCase()}.us`); }) }); console.log(filterData);

O cree primero un Conjunto de símbolos coincidentes, que preferiría para una menor complejidad.

 const array1 = [ { title: 'Stock market news', symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'], }, { title: 'Neil Young urges Spotify', symbols: ['SPOT.US', '639.F', '639.XETRA'] }, { title: 'Neil Young urges Spotify', symbols: ['AAPl.US', '639.F', '639.XETRA'] } ] const array2 = [ {Code: "AAPL"}, {Code: 'SPOT'} ]; const codesToFind = new Set(array2.map(({ Code }) => Code.toLowerCase() + '.us')); const filterData = array1.filter( ({ symbols }) => symbols.some( sym => codesToFind.has(sym.toLowerCase()) ) ); console.log(filterData);

about 4 years ago · Juan Pablo Isaza Report

0

Podríamos usar un enfoque de alternancia de expresiones regulares aquí:

 const array1 = [ { title: 'Stock market news', symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'], }, { title: 'Neil Young urges Spotify', symbols: ['SPOT.US', '639.F', '639.XETRA'] }, { title: 'Neil Young urges Spotify', symbols: ['AAPL.US', '639.F', '639.XETRA'] } ]; const array2 = [{Code: "AAPL"}, {Code: "SPOT"}]; var regex = new RegExp("\\b(?:" + array2.reduce((x, y) => x.Code + "|" + y.Code) + ")\\.US"); console.log(regex); // /\b(?:AAPL|SPOT)\.US/ var output = array1.filter(x => x.symbols.some(e => regex.test(e))); console.log(output);

La estrategia aquí es formar una alternancia de expresiones regulares de símbolos bursátiles, uno de los cuales es obligatorio. Luego filtramos la matriz original, usando some() y la expresión regular para asegurarnos de que cualquier coincidencia tenga al menos un símbolo de cotización requerido.

about 4 years ago · Juan Pablo Isaza Report

0

Si realiza esta búsqueda varias veces, sería mejor crear un índice de símbolos y consultarlo.

Por ejemplo...

 const array1 = [{"title":"Stock market news","symbols":["SPY.US","GSPC.INDX","DJI.INDX","CL.COMM","IXIC.INDX","NQ.COMM","ES.COMM"]},{"title":"Neil Young urges Spotify","symbols":["SPOT.US","639.F","639.XETRA"]},{"title":"Neil Young urges Spotify","symbols":["AAPl.US","639.F","639.XETRA"]}] const array2 = [{Code: "AAPL"},{Code: 'SPOT'}] // utility function to write into the index const writeIndex = (map, key, entry) => { const normalisedKey = String.prototype.toUpperCase.call(key) if (!map.has(normalisedKey)) map.set(normalisedKey, new Set()) map.get(normalisedKey).add(entry) } const symbolIndex = array1.reduce((map, entry) => { // convert all symbols to tokens // eg AAPL.US becomes ["AAPL.US", "AAPL", "US"] const keys = entry.symbols.flatMap(symbol => [symbol, ...symbol.split(".")]) // add the entry for each symbol token keys.forEach(key => writeIndex(map, key, entry)) return map }, new Map()) // pull unique items out of the index for the given codes const queryIndex = codes => Array.from(new Set(codes.flatMap(code => [...symbolIndex.get(code) ?? []] ))) console.log(queryIndex(array2.map(({ Code }) => Code)))
 .as-console-wrapper { max-height: 100% !important; }


Alternativamente, puede usar una cláusula some anidada con una cadena que incluye verificación para ver si el símbolo contiene su código.

 const array1 = [{"title":"Stock market news","symbols":["SPY.US","GSPC.INDX","DJI.INDX","CL.COMM","IXIC.INDX","NQ.COMM","ES.COMM"]},{"title":"Neil Young urges Spotify","symbols":["SPOT.US","639.F","639.XETRA"]},{"title":"Neil Young urges Spotify","symbols":["AAPl.US","639.F","639.XETRA"]}] const array2 = [ {Code: "AAPL"}, {Code: 'SPOT'} ] const normalise = str => str.toUpperCase() const normalisedCodes = array2.map(({ Code }) => normalise(Code)) const filtered = array1.filter(({ symbols }) => normalisedCodes.some(code => symbols.some(symbol => normalise(symbol).includes(code)) ) ) console.log(filtered)
 .as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!