0

I have soo many nested arrays like this

[['branch',12,'name','cofee'],['state',15,'name','tea'],['Country',12,'name','tea']['branch',15,'name','Choclate']]

I want to filter array which is having the element branch so result ll be like this

[['branch',12,'name','cofee'],['branch',15,'name','Choclate']]

can anybody help me on this

3 Answers 3

3

You should provide a predicate to filter which checks if the array contains 'branch'.

If you can use ES6, I would do:

const data = [
  ['branch', 12, 'name', 'cofee'],
  ['state', 15, 'name', 'tea'],
  ['Country', 12, 'name', 'tea'],
  ['branch', 15, 'name', 'Choclate']
];

const processed = data.filter(d => (d.indexOf('branch') > -1));

console.log(processed);

If you can't use ES6:

const data = [
  ['branch', 12, 'name', 'cofee'],
  ['state', 15, 'name', 'tea'],
  ['Country', 12, 'name', 'tea'],
  ['branch', 15, 'name', 'Choclate']
];

const processed = data.filter(function (d) {
  return d.indexOf('branch') > -1;
});

console.log(processed);

Sign up to request clarification or add additional context in comments.

Comments

0

You are missing a comma in your array. You are dealing with a 2d array, a simple object to work with really. Just use a for loop looking for item [0] in each array.

var div = document.createElement("div");
var myArray = [['branch',12,'name','cofee'],['state',15,'name','tea'],['Country',12,'name','tea'],['branch',15,'name','Choclate']];

var filteredArray = [[]];

for (var i = 0; i < myArray.length; i++) {
    if(myArray[i][0] === 'branch'){
        filteredArray.push(myArray[i]);

    }
}

var t = document.createTextNode(filteredArray);

div.appendChild(t);
document.body.appendChild(div);

Comments

0

Well a modern approach is ;

var data = [['branch',12,'name','cofee'],['state',15,'name','tea'],['Country',12,'name','tea'],['branch',15,'name','Choclate']],
filtered = data.filter(f => f.includes("branch"));
console.log(filtered);

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.