Home > Net >  From an array, find the array that has the true values for the objects
From an array, find the array that has the true values for the objects

Time:07-02

Given array: const array = [{1: true},{2: false},{3: true},{}.....];

Filter the given array by only including objects with values of true.

Looking for the shortest solution.

CodePudding user response:

const onlyTrue = array.filter((el, ind) => el[ind   1] === true);

This will work only if indexes in array objects are ordered and starting from 1, as it is in your example.

CodePudding user response:

Assumptions (based on what's in your example):

  • Each object in the array only has at least 1 property in it
  • The first property on each object is the one we care about
  • The property in each object is different every time
const array = [{1: true},{2: false},{3: true}];
const results = array.filter(item => Object.values(item)[0]);

If you want to avoid any false positives from truth-y values (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy), then change the filter call to this instead:

const results = array.filter(item => Object.values(item)[0] === true);

CodePudding user response:

const array = [{1: true},{2: false},{3: true}];
const array2 = [];
array.forEach(filterTrue);
function filterTrue(item){
    for(x in item){
        if(item[x]===true){
            array2.push(item);
        }
    }
}
console.log(array2);

Hope this helps you.
  • Related