Joining strings from different columns

Joining strings from different columns

amahatoamahato Posts: 4Questions: 1Answers: 0
edited November 12 in Free community support

Code:

var headings = ["first name", "last name", "age"];
var firstNameIdx = headings.findIndex(h => h.toLowerCase() === 'first name');
var surnameIdx = headings.findIndex(h => h.toLowerCase() === 'last name');
var shouldCombine = firstNameIdx !== -1 && surnameIdx !== -1;
var columns = headings.map(function (header, index) {
var config = { data: index };
if (shouldCombine && index === firstNameIdx) {
    config.title = 'Full Name';
} else {
    config.title = header;
}
return config;
});

// Build columnDefs array
var columnDefs = [];

if (shouldCombine) {
columnDefs.push({
    targets: firstNameIdx,
    render: (data, type, row) => data + ' ' + row[surnameIdx],
});
}
columnDefs.push(
{
    targets: 1,
    type: 'html'
},
);

if (shouldCombine) {
columnDefs.push(
    { visible: false, targets: [surnameIdx] },
);
}

lt = $('#contentDataTable table').DataTable({
columns,
columnDefs,});

Answers

  • allanallan Posts: 65,397Questions: 1Answers: 10,858 Site admin

    You haven't provided any details beyond the title, so it is hard to know what the specific issue is, what your data format is, etc, but you might have to have a look at this example which combines the first_name and last_name data points from the loaded JSON data into a single column.

    Allan

  • amahatoamahato Posts: 4Questions: 1Answers: 0

    I'm have multiple spreadsheet with different data. One of them have first name and last name. so I want to display it as full name.

  • amahatoamahato Posts: 4Questions: 1Answers: 0

    My current code is only displaying the first name.

  • amahatoamahato Posts: 4Questions: 1Answers: 0

    Hi @allan,
    Thanks for your quick response. I tried to implement a similar approach; however, it didn’t work.
    My current code is a generic one that displays multiple spreadsheets on my website. Now I want to join the strings from two different columns and display them as one for this particular spreadsheet. The issue is that it’s displaying data from either one column or the other, but not the combined result.

  • kthorngrenkthorngren Posts: 22,354Questions: 26Answers: 5,137

    Can you provide a running test case showing what you are trying so we can help debug?
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Seems like this should work:

    columnDefs.push({
        targets: firstNameIdx,
        render: (data, type, row) => data + ' ' + row[surnameIdx],
    });
    

    But without seeing a running example it's hard to guess what surnameIdx is and if row[surnameIdx] points to the desired data. Try placing a browser breakpoint in your render function to debug the values being returned in the columns.render function.

    Kevin

Sign In or Register to comment.