0

I am experiencing unexpected behaviour of push function. The problem is with the latest line of code cited below.

export enum non_searchFieldsNames {
    language = 'language',
    categories = 'categories',
    subtitle = 'subtitle',
    publishedDate = 'publishedDate',
    id = 'id',
}
enum columnsEnum {
    title,
    authors,
    language,
    categories,
    subtitle,
    publishedDate,
}

function toArray(obj: header | contentCategories | sourceFields) {
    return Object.entries(obj)
        .sort((a, b) => {
            return +a - +b;
        })
        .map(item => item[1]);
}

let sourceFieldsObject: sourceFields = {
    [columnsEnum.title]: searchFieldsNames.title,
    [columnsEnum.authors]: searchFieldsNames.authors,
    [columnsEnum.language]: non_searchFieldsNames.language,
    [columnsEnum.categories]: non_searchFieldsNames.categories,
    [columnsEnum.subtitle]: non_searchFieldsNames.subtitle,
    [columnsEnum.publishedDate]: non_searchFieldsNames.publishedDate,
};

const sourceFieldsArray = toArray(sourceFieldsObject).push(non_searchFieldsNames.id);


The problem is with the latest line of code. The value I do receive here is 7. When I simplify it like this

const sourceFieldsArray = toArray(sourceFieldsObject)

I receive an array(however, without the value I try to add, of course).

When I split the logic

const sourceFieldsArray = (toArray(sourceFieldsObject));
sourceFieldsArray.push(non_searchFieldsNames.id);

I get what I wanted. Anyway, I would like to have it as one-liner. So, what is my error? I have tried also

const sourceFieldsArray (toArray(sourceFieldsObject)).push(non_searchFieldsNames.id)

But it does not help.

1
  • 2
    The expression is evaluated left to right, last the function push which doesn't return the array. Commented Jul 2, 2022 at 11:52

1 Answer 1

1

push modifies the main array directly, and it does not return a new array as you expected, but the count of items in that array.

You can check the below demo for push's returned value

const array = [1,1,1] //3 items

const count = array.push(1) //1 more item

console.log(count) //total is 4 items

If you want to have a one-liner, you can try the cloning approach with the spreading operator

const sourceFieldsArray = [...toArray(sourceFieldsObject), non_searchFieldsNames.id]

Side note that this approach means you're creating a new array completely, so you need to be aware of some performance situations with a huge array.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.