hi,
can any one help me on below requirement:
i have 2 arrays as arra1 = [11,1A,1V,BD]
arra2 = [11,22,1A,CD]
i want to sort this and take the similar items
hi,
can any one help me on below requirement:
i have 2 arrays as arra1 = [11,1A,1V,BD]
arra2 = [11,22,1A,CD]
i want to sort this and take the similar items
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Prasad RaveendranRank #320 · 7.8K reputationPosted Oct 18, 2023, 9:50 PM EDT
To find the similar items between these arrays, you can use JavaScript's
filtermethod along with theincludesmethod. Here's the code to do that:const commonItems = array1.filter(item => array2.includes(item));This code will filter the elements of
array1and create a new arraycommonItemsthat contains only the elements that are also present inarray2. In this example,commonItemswill be['11', '1A'], as these are the values that are present in both arrays.If you want the result to be sorted, you can sort the
commonItemsarray like this:commonItems.sort();Now,
commonItemswill be['11', '1A']in sorted order.Sarthak VarshneyRank #46 · 32K reputationPosted Oct 19, 2023, 12:51 AM EDT
array1 = ["11", "1A", "1V", "BD"] array2 = ["11", "22", "1A", "CD"] # Sort the arrays array1.sort() array2.sort() # Find the common elements common_elements = [] i = 0 j = 0 while i < len(array1) and j < len(array2): if array1[i] == array2[j]: common_elements.append(array1[i]) i += 1 j += 1 elif array1[i] < array2[j]: i += 1 else: j += 1 print(common_elements)Vishal YelveRank #178 · 13.6K reputationPosted Oct 20, 2023, 9:45 AM EDT
Hi Murali,
Try this
var concatArraysUniqueWithSort = function (thisArray, otherArray) { var newArray = thisArray.concat(otherArray).sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }); return newArray.filter(function (item, index) { return newArray.indexOf(item) === index; }); }; var arr1 = ['11','1A','1V','BD']; var arr2 = ['11','22','1A','CD']; var arrAll = concatArraysUniqueWithSort(arr1, arr2); console.log(arrAll);