Javascript array search and filter

72 Views Asked by At

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  *****  
});

2

There are 2 best solutions below

0
Barmar On BEST ANSWER

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>

0
trincot On

You could create an object that represents the opposite relation:

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

const transposed = myarray
    .flatMap(Object.entries)
    .flatMap(([key, values]) => values.map(value => [value, key]))
    .reduce((acc, [value, key]) => ((acc[value] ??= []).push(key), acc), {});

console.log(transposed);