0

I got this input

    var input=[ "Axel",
                4,
                4.21,
                { name : 'Bob', age : 16 },
                { type : 'fish', model : 'golden fish' },
                [1,2,3],
                "John",
                { name : 'Peter', height: 1.90}          ];

and the Result must be this one

    [ { name : 'Bob', age : 16 },
      { type : 'fish', model : 'golden fish' },        
      { name : 'Peter', height: 1.90}            ];
5
  • 2
    And where did Axel and John go? Commented Mar 27, 2015 at 15:25
  • 2
    are you trying to remove all elements that are not an object? Commented Mar 27, 2015 at 15:29
  • yes, im trying to get only the objects Commented Mar 27, 2015 at 15:35
  • Look at the answer from Paul below, that should solve your issue. Commented Mar 27, 2015 at 15:40
  • toretto, there is a fiddle with Paul's answer below, in my comment, that might help you out. Commented Mar 27, 2015 at 18:39

2 Answers 2

2

Using Array.prototype.filter, only keep Objects which are not Arrays

var input = ["Axel",
    4,
    4.21,
    {name: 'Bob', age: 16},
    {type: 'fish', model: 'golden fish'},
    [1, 2, 3],
    "John",
    {name: 'Peter', height: 1.90}
];

input = input.filter(function (e) {
    return (typeof e === 'object') && !Array.isArray(e);
}); /*
[
    {"name": "Bob", "age": 16},
    {"type": "fish", "model": "golden fish"},
    {"name": "Peter", "height": 1.9}
]
*/
Sign up to request clarification or add additional context in comments.

4 Comments

posted this 49secs after you :) Just deleted mine and upvoted yours =D
doesnt work ... "TypeError: undefined is not a function"
What browser? May be Array.isArray is not implemented in your browser
I created a Fiddle for this. Paul, you needed to set the input variable at the filter line so the variable is updated (I made the edit). I ran this in chrome and ie9, it worked good.
0

Try using array filter to remove the unwanted elements. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

To remove all integers

var filteredList = input.filter(function(val) {
    return isNaN(val);
}):
/*
filteredList is now =
{ name: 'Bob', age: 16 },
{ type: 'fish', model: 'golden fish' },
[ 1, 2, 3 ],
'John',
{ name: 'Peter', height: 1.9 } ]
*/

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.