Search code examples
arrayschartshighchartstagscloud

Highcharts wordcloud : how to eliminate words based on their weight


I need to eliminate words based on their weight. I tried to use word.weight before arr.push to avoid that words with weight lower than 3 goes into array ... but this doesn't work !

<script>
    lines = text.replace(/[():'?0-9]+/g, '').split(/[,\. ]+/g),
    data = lines.reduce((arr, word) => {
        let obj = Highcharts.find(arr, obj => obj.name === word);
        if (obj) {
            obj.weight += 1;
        } else {
            obj = {
                name: word,
                weight: 1
            };
            
            if(word.weight> 3) {
                
                    arr.push(obj);
                  
            }

        }
        return arr;
    }, []);
</script>

Solution

  • Your code won't be able to push a single element into array because you only push when the element is not yet contained in the array. But in that case, you create an obj with weight 1, which won't be pushed, because of your weight > 3 condition. I'd suggest to push all words to the array and then filter out those with a weight of 3 or less

    Furthermore word in you case is a string and a string doesn't have a weight property. You probably meant checking if (obj.weight > 3) instead ...

    <script>
        lines = text.replace(/[():'?0-9]+/g, '').split(/[,\. ]+/g),
        data = lines.reduce((arr, word) => {
            let obj = Highcharts.find(arr, obj => obj.name === word);
            if (obj) {
                obj.weight += 1;
            } else {
                obj = {
                    name: word,
                    weight: 1
                };
                arr.push(obj);
            }
            return arr;
        }, []).filter(x => x.weight > 3);
    </script>