I also needed my results to be unique. I supplied a list of item names and only had room to associate one internal ID with each name in that list. Here is how I solved that problem.
In my initial test, I included 190 item names in my arrayOfNames. All names in that list matched items where display names did not match item name in the databsae. Some had ‘(COPIED)’ in the item name and were still active. In summary, it was a good sample set.
My test ran is a couple of seconds. It matched 100% of my arrayOfNames (190 out of 190). We have about 40,000 items in our item’s table in NetSuite. This was in sandbox too! So, it was pretty fast.
Here is the code in a form you can paste directly into debugger.
require([‘N/log’, ‘N/search’],
function (log, search) {
function getItemIdsByName(arrayOfNames) {
var myFilters = new Array();
arrayOfNames.forEach(
function (name) {
if (myFilters.length > 0) myFilters.push(‘or’);
myFilters.push([
[‘itemid’, ‘is’, name],
‘or’,
[‘displayname’, ‘is’, name]
])
}
)
var mySearch = search.create({
type: search.Type.ITEM,
columns: [‘internalid’, ‘itemid’, ‘displayname’],
filters: [
[‘isinactive’, ‘is’, false],
‘and’,
[‘itemid’, ‘doesnotcontain’, ‘(COPIED)’],
‘and’,
[myFilters]
]
});
var myPages = mySearch.runPaged({ pageSize: 1000 });
var matches = new Array();
for (var i = 0; i < myPages.pageRanges.length; i++) {
var myPage = myPages.fetch({ index: i });
myPage.data.forEach(
function (match) {
var itemid = match.getValue(‘itemid’);
var displayname = match.getValue(‘displayname’);
var internalid = match.getValue(‘internalid’);
matches.push({
itemid: itemid,
displayname: !displayname ? itemid : displayname,
internalid: internalid
})
return true;
}
)
}
var results = new Array();
arrayOfNames.forEach(
function (name) {
var firstMatch = matches.filter(
function (a) {
// If the itemid or the displayname matches a name in arrayOfNames, it matches.
if (a.itemid === name) return true;
if (a.displayname === name) return true;
return false;
}
)
if (firstMatch && firstMatch.length > 0) {
results.push({
itemid: name,
internalid: firstMatch[0].internalid
})
}
}
)
return results;
}
var arrayOfNames = [
‘Your Item Name here #1’,
‘Your Item Name here #2’,
‘Your Item Name here #3’,
‘Your Item Name here #190’,
];
var matches = getItemIdsByName(arrayOfNames);
// The log function is slow. Don’t call it more than once if you are
// interested in response time.
log.debug(‘Matched ‘ + matches.length + ‘ out of ‘ + arrayOfNames.length);
// If you want to see results and not measure response time.
// matches.forEach(
// function (match) {
// log.debug(‘itemid: ‘ + match.itemid + ‘, internalid: ‘ + match.internalid);
// }
// )
}
)