0

Can you please show me the best way to process/ manipulate this array of hashes using javascript function chaining. I want to filter the data and return ONLY an array of hashes that contains data that in NOT all 0’s.


data = [
    {name: "apple", data: [0, 0, 0]},
    {name: "banana", data: [1, 0, 2]},
    {name: "carrot", data: [0, 0, 0]},
    {name: "pineapple", data: [0, 0, 3]},
]

//result after filtering

data = [
    {name: "banana", data: [1, 0, 2]},
    {name: "pineapple", data: [0, 0, 3]},
]

I was thinking something along the lines of

data.filter((hash,i) => {hash.data.every((elem,i)=> elem == 0); 
4
  • I was thinking something along the lines of data.filter((hash,i) => {hash.data.every((elem,i)=> elem == 0); return hash } ) but this doesn’t work and I would like some guidance. Thank you again! Commented Aug 2, 2019 at 23:28
  • Don't use curly quotes in JavaScript code, use ASCII quotes. Commented Aug 2, 2019 at 23:31
  • Use .filter and use the every or some method in the filtering function. Commented Aug 2, 2019 at 23:33
  • Why does the third element have a carrot property instead of data? Is that supposed to be the name? Commented Aug 2, 2019 at 23:37

2 Answers 2

1

This should do it

const data = [{name:”apple”,data:[0,0,0]}, {name:”banana”,data:[1,0,2]}, {name:””,carrot:[0,0,0]}, {name:”pineapple”,data:[0,0,3]}, ]

const nonzero = data.filter(({data}) => data.some(Boolean));
Sign up to request clarification or add additional context in comments.

Comments

0

You were almost right. You need to invert the result of the every test, since you want the elements that aren't all zero; you could also use some and test for non-zero. Also, don't put curly braces around the body of the function if you just want to return the result of the expression.

data = [{
    name: "apple",
    data: [0, 0, 0]
  },
  {
    name: "banana",
    data: [1, 0, 2]
  },
  {
    name: "carrot",
    data: [0, 0, 0]
  },
  {
    name: "pineapple",
    data: [0, 0, 3]
  },
];
console.log(data.filter(hash => !hash.data.every(elem => elem == 0)));

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.