mercredi 30 août 2017

Iterate over array of arrays to match objects in response array and then pull them out into new array

I am trying to pass a response array and also another array that has arrays that will match certain objects in the response array. As it is doing that it will take those matched objects, randomize them and then add them to a new array, repeating as it goes through the objects of the passed arrays. After finding matches and randomizing it will need to randomize the remaining response array and add it to the new array. This will need to happen in chunks, first set of matched objects, second, third, etc... I have it matching key and values currently, but since an object’s properties are not ordered it is creating issues. Any help is greatly appreciated.

let sortObject = [
    ['company', 'some_name'],
    ['page_type', 'some_page']
];

function (array, sortObject) {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;

// Find matching properties in array
function findByMatchingProperties (array, properties) {
    return array.filter(function (entry) {
        return Object.keys(properties).every(function (key) {
            return entry[key] === properties[key];
        });
    });
}

// Use sortObject to array of arrays with objects to match
let results = findByMatchingProperties(array, sortObject);

function _randomizeArray (results) {
    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = results[currentIndex];
    results[currentIndex] = results[randomIndex];
    results[randomIndex] = temporaryValue;
}

// While there remain elements to shuffle.
while (0 !== currentIndex) {
    _randomizeArray(results);
    return results;
}

};




Aucun commentaire:

Enregistrer un commentaire