简体   繁体   中英

array intersection with nested arrays

Pretty new to functional javascript, so please bear with me.

Edited for more information.

I have an array that is being created from a csv file using:

var url = "URL-TO-CSV/report.csv";

var request = new XMLHttpRequest();  
request.open("GET", url, false);   
request.send(null);  

var csvData = new Array();
var jsonObject = request.responseText.split(/\r?\n|\r/);
for (var i = 0; i < jsonObject.length; i++) {
csvData.push(jsonObject[i].split(','));
}

Which results in an array of arrays, not keyed pairs.

[
  ['stringID-1',"string","string","string","string"],
  ['stringID-2',"string","string","string","string"],
  ['stringID-3',"string","string","string","string"]
]

And another array generated from a list of id's to be matched which is currently using jQuery (because I haven't figured out raw Javascript for it yet), like so:

 $("input:checkbox:not(:checked)").each(function () {
     
        var $this = $(this);
        matchData.push($this.attr("id"));
           
})

Which results in the below type array.

['stringID-1','stringID-3']

I have tried varying filter syntax but to no avail. If I don't get an error I get an empty array.

I need to intersect the two and return an array of the matching arrays from csvData so I can then parse it to HTML in an each loop.

I cannot seem to be able to figure this out and would love some direction. Thanks in advance

I think all you need is a filter to restrict to rows where the first indexed is found in the other array:

 let csvData = [ ['item-to-match-string-id-1', "string data", "string data", "string data"], ['item-to-match-string-id-2', "string data", "string data", "string data"], ['item-to-match-string-id-3', "string data", "string data", "string data"], ['item-to-match-string-id-4', "string data", "string data", "string data"], ['item-to-match-string-id-5', "string data", "string data", "string data"], ] let matchData = ['item-to-match-string-id-2','item-to-match-string-id-5'] let matching = csvData.filter(row => matchData.includes(row[0])) console.log(matching)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM