Sparlarva
Sparlarva

Reputation: 804

iterate through nested array to match IDs

I have a set of data which is nested arrays, these arrays may be empty or they may infact contain an ID, if one of the arrays ID's matches the ID im comparing it with, I want to take all of the data inside that array which matched and assign it to a variable to be used...

example:

data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]]

id = 123

matchedArray =
  for (var i = 0; i < potentialEvents.length; i++) {
    for (var j = 0; j < potentialEvents[i].length; j++) {

      if (id === potentialEvents[i].id) {
        return;
      }
    }
  }
console.log(matchedArray)

I'm trying to have it so matchedArray will be the array with thhe matched IDs!!

if you can help, thank you a lot!

Upvotes: 3

Views: 570

Answers (3)

Styx
Styx

Reputation: 10076

I'd recommend to use .some rather then .filter/.map/.flatMap. The main benefit is that it allows to stop traversing array when element is found.

On big arrays with a lot of data it will be more efficient (≈50 times faster): jsperf test

const data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]]

const id = 123;
let matchedArray = null;

data.some((a) => {
  return a.some((v) => {
    if (v != null && v.id == id) {
      matchedArray = a;
      return true;
    }
  });
});

console.log(matchedArray);

Upvotes: 1

Jamiec
Jamiec

Reputation: 136074

You can do this with a combination of .map, .filter and .flat

var data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]]

var id = 123;

var matchedArray = data.map( arr => {
   return arr.filter(x => x.id == id);
}).flat();

console.log(matchedArray);

Upvotes: 3

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can use Array#filter method to filter the inner array and Array#flatMap method to concatenate filtered array into one.

let data = [[],[],[],[],[],[],[],[],[{"id":"123","name":"DARES HOUSE 2019","startDate":null,"endDate":null,"country":null,"city":null,"type":"Event","members":null}],[],[],[],[],[],[],[],[],[],[],[]];
let id = 123;

let matchedArray = data.flatMap(arr => arr.filter(obj => obj.id == id))
console.log(matchedArray)

Upvotes: 2

Related Questions