Return new array with specific values using map()

Please help me with a solution to extract in a new array only the specific object that has the paramenter checked: true.
See the example below:

    {nodeName: 'node1', nodeId: 1, checked: false },
    {nodeName: 'node2', nodeId: 2, checked: true },
    {nodeName: 'node3', nodeId: 3, checked: false },
    {nodeName: 'node4', nodeId: 4, checked: true },
    {nodeName: 'node5', nodeId: 5, checked: false },
    {nodeName: 'node6', nodeId: 6, checked: true },
]

let checkedNodes = nodes.map(node => {
    let options = {
        "name": node.nodeName,
        "id": node.nodeId,
        "checked": node.checked
    }
    
    return options;
})

This will return all the nodes 🙁
How can I make the verification, in order to return the array like this?

[
    {
        "name": "node2",
        "id": 2,
        "checked": true
    },
    {
        "name": "node4",
        "id": 4,
        "checked": true
    },
    {
        "name": "node6",
        "id": 6,
        "checked": true
    }
]

>Solution :

You can’t do this with just .map(). .map() will always return an array the same exact size of the input array.

You can either .filter() the array then .map(), or use .reduce().

In this case, .filter() is going to be the easiest, both to read and write. Just include it before the .map() call:

const nodes = [
  {nodeName: 'node1', nodeId: 1, checked: false },
  {nodeName: 'node2', nodeId: 2, checked: true },
  {nodeName: 'node3', nodeId: 3, checked: false },
  {nodeName: 'node4', nodeId: 4, checked: true },
  {nodeName: 'node5', nodeId: 5, checked: false },
  {nodeName: 'node6', nodeId: 6, checked: true },
]

const checkedNodes = nodes
  .filter(node => node.checked)
  .map(node => ({
    name: node.nodeName,
    id: node.nodeId,
    checked: node.checked
  }));
  
console.log(checkedNodes);

The only downside to this approach is it’ll iterate over your list possibly twice, which is fine for small sets like this. If it was a large set of nodes, you’d want to consider using .reduce(), which could do it in one loop (at the cost of readability).

const nodes = [
  {nodeName: 'node1', nodeId: 1, checked: false },
  {nodeName: 'node2', nodeId: 2, checked: true },
  {nodeName: 'node3', nodeId: 3, checked: false },
  {nodeName: 'node4', nodeId: 4, checked: true },
  {nodeName: 'node5', nodeId: 5, checked: false },
  {nodeName: 'node6', nodeId: 6, checked: true },
]

const checkedNodes = nodes
  .reduce((acc, node) => {
    if (node.checked) {
      acc.push({
        name: node.nodeName,
        id: node.nodeId,
        checked: node.checked
      })
    }

    return acc;
  }, []);

console.log(checkedNodes);

Leave a Reply