1

i'm trying to do a javascript filter to an array but somehow im returning one array when it needs to be separated (0 first data 1 second data) so that I can process it easily in a another loop. I hope the below makes sense. Thank you in advance for any help.

JSON INPUT

[
    {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
]

INTO data ARRAY THE FILTERED

function filterByProperty(array, prop, value){
    var filtered = [];

    for (var i = 0; i < array.length; i++) {
        var obj = array[i];

        for (var key in obj) {

            if (typeof(obj[key] === "object")) {
                var item = obj[key];

                if(obj[prop] == value){
                    filtered.push(item);
                }
            } else {
              console.log("not object");
            }
        }
    }    

    return filtered;
}


var filtereddata = filterByProperty(data, "type", "car");
console.log(filtereddata);

When I run this, I only see one array not two?

6
  • 2
    I don't understand the question. What is your expected output? Commented Jul 19, 2018 at 16:45
  • not sure how to say it but something like this [ { "id": 2, "title": "BMW 4 series", "type": "car" }, { "id": 4, "title": "Audi A3", "type": "car" } ] Commented Jul 19, 2018 at 16:48
  • 2
    And that is one array. Why would you expect 2 arrays? Commented Jul 19, 2018 at 16:49
  • @charlietfl Fairly certain he meant two objects Commented Jul 19, 2018 at 16:50
  • You'll probably make your life a lot easier if you use the built in filter method available on arrays. You don't seem to need 2 different arrays, just one with objects that match a certain criterion, namely the type value of specific objects within the array you're filtering. Commented Jul 19, 2018 at 16:51

8 Answers 8

2

You're only pushing values to one array and returning one array. That's why you only get one array...

try it like this:

function filterProp(data, prop){
    return data.filter(el => {
        return el.type === prop
    })
}

Then just use like:

console.log(filterProp(data, 'car'))

Or if you need to specify the key:

function filterProp(data, key, prop){
    return data.filter(el => {
        return el[key] === prop
    })
}

console.log(filterProp(data, 'title', 'BMW'))
Sign up to request clarification or add additional context in comments.

1 Comment

This is the only answer that actually answers the PO's question "When I run this, I only see one array not two?"
2

In ES6, arrays have builtin method .filter to filter items. Its sugar syntax for Array.prototype.filter()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const data = [
    {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
];

const filter = (d, prop, value) => d.filter((obj) => obj[prop] === value);
const filtereddata = filter(data, "type", "car");

console.log(filtereddata);

Comments

2

First a note about typeof which is a keyword, not a function.

Using it like a function means it evaluates obj[key] == "object" first.
Since that evaluates to false, typeof then returns boolean because typeof false is boolean.

boolean is a truthy value, so you never hit your else clause.

That said, you can fix your function by:

  • eliminating the typeof check.
  • adding another check to make sure the key matches the passed in prop.
  • and pushing the obj into the array to return.

function filterByProperty(array, prop, value) {
    var filtered = [];
    for (var i = 0; i < array.length; i++) {
        var obj = array[i];
        for (var key in obj) {
            if (key === prop && obj[prop] == value) {
                filtered.push(obj);
            }
        }

    }

    return filtered;

}


const data = [{
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
];

var filtereddata = filterByProperty(data, "type", "car");

console.log(filtereddata);

Alternatively, you could use Array.filter instead:

const filterByProperty = (arr, prop, value) => arr.filter(o => o[prop] && o[prop] === value);

const data = [{
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
];

const filtered = filterByProperty(data, 'type', 'car');
console.log(filtered);

Comments

2

As an alternative to the other answers, I have changed your code slightly to work. Instead of moving through each key in the each 'vehicle' object it just checks for each vehicles prop equaling value in the first for loop.

Heres the code:

var data = [
        {
            "id": 1,
            "title": "Ford F-150",
            "type": "truck"
        },
        {
            "id": 2,
            "title": "BMW 4 series",
            "type": "car"
        },
        {
             "id": 3,
             "title": "Triumph Scrambler",
             "type": "motorbike"
        },
        {
            "id": 4,
            "title": "Audi A3",
            "type": "car"
        }
    ];    

    function filterByProperty(array, prop, value){
        var filtered = [];
        for(var i = 0; i < array.length; i++){
            var obj = array[i];
            if(obj[prop] == value)
                filtered.push(obj);
            else{
                console.log("not a " + value);
            }
        }    
        return filtered;
    }


    var filtereddata = filterByProperty(data, "type", "car");

    console.log(filtereddata);

hope this helps somebody!

2 Comments

Put the code in your answer. Use a stack-snippet so it can be seen and run right here, instead of having to go to jsfiddle.
Roger that Stephen
1

You can use Array.filter to filter by property value

var data = [
      {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck",
        "date": "2017-12-23"
      },
      {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car",
        "date": "2017-12-22"
      },
      {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike",
        "date": "2017-12-21"
      },
      {
        "id": 4,
        "title": "Audi A3",
        "type": "car",
        "date": "2017-12-20"
      }
];
        
      function filterByProperty(array, prop, value){
          return newArray = array.filter(function (el) {
            return el[prop] == value;
          });
      }
      function compare(a,b) {
        if (new Date(a.date) < new Date(b.date))
          return -1;
        if (new Date(a.date) > new Date(b.date))
          return 1;
        return 0;
      }

      var filtereddata = filterByProperty(data, "type", "car");
      console.log(filtereddata.sort(compare));

6 Comments

Thank you worked perfectly. What if it had a date - sort by date too [ { "id": 2, "date": "20/12/2017" "title": "BMW 4 series", "type": "car" }, { "id": 4, "date": "20/11/2017" "title": "Audi A3", "type": "car" } ]
I didn't get you. Did you mean date in the property value ?
sorry i meant filter with date
So your filtering like within your example but with date sort too
Check my answer. It is now sorted by date after filter.
|
1

Try using Array.filter(callback)

function filterByProperty(array, prop, value) {
    var filtered = array.filter(item => {
      item[prop] === value;
    }
    return filtered;
}

var filtereddata = filterByProperty(data, "type", "car");

console.log(filtereddata);

Comments

1

you can use this function:

var data =[
        {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
        },
        {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
        },
        {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
        },
        {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
        }
        ]
        
        filterByProperty(data, 'type', 'car');
        function filterByProperty(data, prop, value){
        	for(i=0; i<data.length; i++){
          	if(data[i][prop]==value){
            	console.log(data[i]);
            }
          }
        }

Comments

1

As manavM said the internal array.filter class is made for this. The original array remains untouched. The second array filteredArr contains all of the items that returned a true to your return statement.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://www.w3schools.com/jsref/jsref_filter.asp

function filterByProperty(arr, prop, val) {
    const filteredArr = arr.filter(function (v) {
      return typeof v === 'object' && v[prop] == val;
    });
    console.log(arr);
    console.log(filteredArr);
};
filterByProperty([{
    "id": 1,
    "title": "Ford F-150",
    "type": "truck"
    },{
    "id": 2,
    "title": "BMW 4 series",
    "type": "car"
    },{
    "id": 3,
    "title": "Triumph Scrambler",
    "type": "motorbike"
    },{
    "id": 4,
    "title": "Audi A3",
    "type": "car"
    }], "type", "car");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.