Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript array search and filter

I want to create new array based on keyword.

if my search key word is

  • "align-center" result should be ["align-center"]
  • "align" result should be ["align-left", "align-center", "align-right"]
  • "right" result should be ["align-right"]
  • "arrow" result should be ["align-left", "align-right"]

const myarray = [
        {
            "align-center": [
                "align",
                "center"
            ]
        },
        {
            "align-justify": [
                "align",
                "justified"
            ]
        },
        {
            "align-left": [
                "align",
                "left",
                "arrow"
            ]
        },
        {
            "align-right": [
                "align",
                "right",
                "arrow"
            ]
        }
    ]

    let results = myarray.filter(function (name) { return  *****  
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First use map() to get the key of each object in the array. Then use filter() to return the ones that match the search string.

let searchKey = 'left';

function search(array, searchKey) {
  return array.map(obj => Object.keys(obj)[0]).filter(key => key.includes(searchKey));
}

console.log(search(myarray, 'align-center'));
console.log(search(myarray, 'align'));
console.log(search(myarray, 'right'));
<script>
  const myarray = [{
      "align-center": [
        "align",
        "center"
      ]
    },
    {
      "align-justify": [
        "align",
        "justified"
      ]
    },
    {
      "align-left": [
        "align",
        "left",
        "arrow"
      ]
    },
    {
      "align-right": [
        "align",
        "right",
        "arrow"
      ]
    }
  ];
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading