Where Art Thou-freecodecamp algorithm topics

Source: Internet
Author: User

Where Art Thou

1. Requirements

    • Write a function that iterates through an array of objects (the first parameter) and returns an array of all objects that contain matching property-value pairs (the second argument).
    • If the returned array contains property-value pairs for the source object, then each property-value pair of this object must exist in the collection object.

2. Ideas

    • Remove the property of source with Object.keys (source)
    • Use Object.keys () to iterate through the properties of the collection all child elements in the for loop, set the mark tag variable, and initially true in a layer loop.
    • Mark becomes false when encountering a collection child element without a Sourse attribute in the For loop or when two corresponding property values are not equal
    • A layer of loops finally, if Mark is true, push the corresponding collection child element to the result array

3. Code

function where(collection, source) {var arr = [];var arrj = Object.keys(source);for(var i = 0; i<collection.length; i++){    var arri = Object.keys(collection[i]);    var mark = true;    for (var j = 0; j < arrj.length; j++){    if (arri.indexOf(arrj[j]) === -1 ||  collection[i][arrj[j]] !== source[arrj[j]]) {        mark =false;    }    }    if (mark){    arr.push(collection[i]);    }}// What‘s in a name?return arr;}where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

4. RELATED LINKS

    • Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Where Art Thou-freecodecamp algorithm topics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.