I have an arrays like:
["oh", 2]
["yes", 2]
["sheet", 2]
["really", 1]
["bro", 1]
["om", 0]
["a", 0]
["to", 0]
i needed to make checkout like second meaning of array doesn’t be a 0, i try with function like if arr != 0 return arr, but it also return an undefined when find a value 0.
How can a make the output like word – number without arrays with 0 value?
For the example i need to output: oh – 2, yes – 2, sheet – 2, really – 1, bro – 1
>Solution :
To filter out the arrays in your example that have a value of 0 for the second element, you can use the Array.filter() method in combination with the Array.join() method.
Here is an example of how you can use these methods to filter out the arrays with a value of 0 for the second element and create a string of the remaining arrays in the format "word – number":
var arr = [ ["oh", 2],
["yes", 2],
["sheet", 2],
["really", 1],
["bro", 1],
["om", 0],
["a", 0],
["to", 0]
];
// Filter out the arrays with a value of 0 for the second element
var filteredArr = arr.filter(function(item) {
return item[1] != 0;
});
// Create a string of the remaining arrays in the format "word - number"
var output = filteredArr.map(function(item) {
return item[0] + " - " + item[1];
}).join(", ");
console.log(output); // "oh - 2, yes - 2, sheet - 2, really - 1, bro - 1"
In this example, the Array.filter() method is used to filter out the arrays with a value of 0 for the second element. The Array.map() method is then used to create a new array of strings in the format "word – number" for each of the remaining arrays, and the Array.join() method is used to concatenate the strings into a single string separated by a comma and a space.