Reputation: 795
Given a reference array of individual numbers and paired numbers in nested arrays.
How would you loop over a data set to determine which numbers are part of a pairing and output them to a new array?
// reference array
let refData = [[1,4],3,10,[8,9],6];
// example 1 data to process
let dataSet = [1, 6, 4, 3];
// expected new outputted array
newData[[1,4],6,3];
// example 2 data to process
let dataSet = [3, 9, 10, 6, 8];
// expected new outputted array
newData[3,[9,8],10,6];
EDITED:
Thank you for your answers.
Based on the responses I attempted to apply this to my working example, but I'm getting a little stuck. Could you please provide me with a little more help to get me over the hill?
// Stored reference data
let invitedGuests = [[9254,9256], 9258, 9261, [9259,9262]];
// Dynamic received data
let guestsArrived = [9254, 9258, 9261, 9256];
let checkedInGuests = []
for (let i = 0; i < invitedGuests.length; i++) {
if (Array.isArray(invitedGuests[i])) {
for (let j = 0; j < invitedGuests[i].length; j++) {
for (let g = 0; g < guestsArrived.length; g++) {
if (playerGroups[i][j] == guestsArrived[g]) {
checkedInGuests[i][j] = guestsArrived[g];
}
}
}
}
I'm hoping to end up with
checkedInGuests = [[9254,9256], 9258, 9261]
Upvotes: 0
Views: 64
Reputation: 1671
Hint: use Array.isArray(item)
to check whether an item is single value or array.
refData.forEach(function(item) {
if (Array.isArray(item)) {
checkDataSet(item);
} else {
checkItemNormally(item);
}
});
Example: Below is what I have tested.
var refData = [[1,4],3,10,[8,9],6];
//var dataSet = [1, 6, 4, 3];
var dataSet = [3, 9, 10, 6, 8];
var result = [];
refData.forEach(function (item) {
if (Array.isArray(item)) {
for (var i = 0; i < dataSet.length; i++) {
if (item.includes(dataSet[i])) {
result.push({
key: item,
value: item
});
break;
}
}
} else {
// individual
if (dataSet.includes(item)) {
result.push({
key: item,
value: item
});
}
}
});
result.forEach(function (item) {
console.log(item.key)
});
Hope this helps you sorting the problem out.
Upvotes: 1