0

I'm writing a code where in I need to do a dynamodb scan and there I need to create a array response with the values, when I do it, it is adding undefined. this is an extension to my previous queestion Confused creating a DynamoDB query

Here is my code.

var results = [];
var array=["a","b"];
for (index = 1; index <= 5; ++index) {
        var params1 = {
        TableName: "MyCatTable",
        FilterExpression: "#rule=:rule",
        ExpressionAttributeNames: {
            "#rule": "rule"
        },
        ExpressionAttributeValues: {
            ":rule": String(index)
        }
};
results.push(dynamodb.scan(params1).promise().then(function (data) {
                if (data.Items.length == 2) {
                    var uw = [];
                    console.log("Entered");
                    for (var i = 0; i < 2; i++) {
                        if (array.indexOf(data.Items[i].category) >= 0) {
                            console.log("pushing");
                            uw.push(data.Items[i].category);
                        }
                    }
                    if (uw.length > 1) {
                        return uw;
                    } else return "x";

                } else {
                    return "x";
                }
            }));
        }
    return Promise.all(results);
}).then((data) => {
    console.log("----------------------");
    console.log(data);
}).catch(err => {
    console.log(err)
})

when I run this code I get the output as

[
  'x',
  ['a', 'b'],
  ['a', 'b'],
  'x',
  'x'
]

here when I remove return "x", the output that I get is

[
  undefined,
  ['a', 'b'],
  ['a', 'b'],
  undefined,
  undefined
]

I want to know if there is a way to get

[
  ['a', 'b'],
  ['a', 'b'],
]
user3872094
  • 3,269
  • 8
  • 33
  • 71

1 Answers1

2

Expanding the comment to an answer.


The problem of removing undefined values from Javascript array has been solved in this question, the simplest way is to use filter function (ES6).

data.filter(d => d !== undefined)

will return the array with undefined values removed.

Also, note that the reason why the undefined values are in the array in the first place is, return nothing returns undefined in Javascript.

user202729
  • 3,358
  • 3
  • 25
  • 36