This question already has answers here:
How to get unique values in an array [duplicate]
(20 answers)
Closed 6 years ago.
I have an array
var myArray = ['1','1','2','2','1','3'] // 6 item
Is there any ways I can return the value of 1 and 2 and 3 ONE time when looping?
//example in pseudocode
var getNumber = [];
var count = 0;
var check = 0;
for(var i in myArray)
{
if(getNumber[check] !== myArray[i])
{
getNumber[count] = myArray[i];
count++;
}
else
{
}
}
and advice to follow up my previous code?
thanks
You should use Array.indexOf and Array.push to check and insert values.
var getNumber = [];
for(var i in myArray)
{
if(getNumber.indexOf(myArray[i]) < 0) //See if the number wasn't found already
{
getNumber.push(myArray[i]);
}
else
{
//This number was found before. Do nothing!
}
}
you could do something like :
function leaveDupes(arry){
var newArry = [], keys={};
for(var i in arry){
if(!keys[arry[i]]){
newArry.push(arry[i]);
keys[arry[i]]=true;
}
}
return newArry;
}
console.log(leaveDupes(['1','1','2','2','1','3'] ))
using underscore.js, you can do something like:
newArry = _.uniq(['1','1','2','2','1','3']);
var obj = {};
for (var i = 0; i < myArray.length; i++) {
if (!obj[myArray[i]]) {
obj[myArray[i]] = true;
console.log(myArray[i]); //these are the unique values
}
}
This will work.
var myArray = ['1','1','2','2','1','3']
var getNumber = {};
var retArray = [];
myArray.forEach(function(val){
if(!getNumber[val]){
getNumber[val] = val;
retArray.push(val);
}
});
return retArray
You can use forEach and indexOf array method to find the unique elements.
var myArray = ['1','1','2','2','1','3','4','4','5'];
var uniqueArray =[]; //A new array which will hold unique values
function _unique(myArray){
myArray.forEach(function(item,index){
if(uniqueArray.indexOf(item) ==-1){ //Check if new array contains item
uniqueArray.push(item)
}
})
}
_unique(myArray);
Related
I am trying to compare the items in "item" array and the copyofOpList array to retrieve the data occurrences in copyofOpList
this is my try:
var _deleteUsedElement1 = function(item) {
for (var i = 0; i < item.length-1; i++){
for (var j = 0; j< $scope.copyofOpList.length-1; j++){
if (item[i].operationCode == $scope.copyofOpList[j].code) {
$scope.copyofOpList.splice(j, 1);
} } } };
$scope.compareArrays = function() {
...Get data from web Service
_deleteUsedElement1(item);
}
the copyofOpList array has 14 elements,and the item array has 2 array
but my code deletes only one occurrence (the first),so please how can I correct my code,to retrieve any occurances in the copyofOpList array comparing to the item array
thanks for help
I'd try to avoid looping inside a loop - that's neither a very elegant nor a very efficient way to get the result you want.
Here's something more elegant and most likely more efficient:
var item = [1,2], copyofOpList = [1,2,3,4,5,6,7];
var _deleteUsedElement1 = function(item, copyofOpList) {
return copyofOpList.filter(function(listItem) {
return item.indexOf(listItem) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [3,4,5,6,7]
}
And since I just noticed that you're comparing object properties, here's a version that filters on matching object properties:
var item = [{opCode:1},{opCode:2}],
copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}];
var _deleteUsedElement1 = function(item, copyofOpList) {
var iOpCodes = item.map(function (i) {return i.opCode;});
return copyofOpList.filter(function(listItem) {
return iOpCodes.indexOf(listItem.opCode) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]
Another benefit of doing it in this manner is that you avoid modifying your arrays while you're still operating on them, a positive effect that both JonSG and Furhan S. mentioned in their answers.
Splicing will change your array. Use a temporary buffer array for new values like this:
var _deleteUsedElement1 = function(item) {
var _temp = [];
for (var i = 0; i < $scope.copyofOpList.length-1; i++){
for (var j = 0; j< item.length-1; j++){
if ($scope.copyofOpList[i].code != item[j].operationCode) {
_temp.push($scope.copyofOpList[j]);
}
}
}
$scope.copyofOpList = _temp;
};
This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 7 years ago.
Below is my code:
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = iaData[i];
loNode.states= [];
}
}
modifyData(laData);
In the Output I can see that [{"fname":"India","states":[]},{"fname":"Germany","states":[]}] the states node is getting appended to the Original Array laData.
Question: How do I prevent "States" node to be appended to the laData?
Solution using Jquery.
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
var modifiedData = [];
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = $.extend(true, {}, iaData[i]); //Doing a Deep copy of the object
loNode.states= [];
modifiedData.push(loNode);
}
return modifiedData;
}
var modifiedData = modifyData(laData);
console.log("Original Data:");
console.log(laData);
console.log("Modified Data");
console.log(modifiedData);
Check your browser console to see the different outputs.
You can see that the output of the initial object does not have states appended to it. and Here is the working JSFiddle
You just have to remove one line:
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = iaData[i];
//loNode.states= []; <-- remove this line
}
}
modifyData(laData);
The commented line is the one adding an empty array to your node.
If you remove it, you will get the structure you wants
This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 7 years ago.
I have this JavaScript array with length 129.
var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]
I would like to find how many times those names appeared in an array and store that information in an array like this:
var counter = [2, 5, 7, ..]
where Karri occured in fullnames array 2 times, Ismo occured 5 times etc. Any ideas about how to do it?
This is the best - and simple - way I can think of:
var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};
for (var i = 0; i < fullnames.length; i++)
{
if (!counts.hasOwnProperty(fullnames[i]))
{
counts[fullnames[i]] = 1;
}
else
{
counts[fullnames[i]]++;
}
}
console.log(counts);
Original Fiddle.
Using an array to store the counts doesn't makes much sense, so I used an object instead.
I am assuming that fullnames is array of strings. If so, you can do it like so:
var occurences = { };
for (var i = 0; i < fullnames.length; i++) {
if (typeof occurences[fullnames[i]] == "undefined") {
occurences[fullnames[i]] = 1;
} else {
occurences[fullnames[i]]++;
}
}
console.log(occurences); // Prints out something like: {"Karri": 2, "Ismo": 5, ...}
var fullnames = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
var counts = [];
fullnames.forEach(function(_item) {
if(typeof counts[_item] === 'undefined') counts[_item] = 1;
else counts[_item]++;
});
var result = [];
for(i in counts) result.push(counts[i]);
console.log(result);
// outputs [3, 3, 5]
This question already has answers here:
How to check if a string "StartsWith" another string?
(18 answers)
Closed 9 years ago.
I have an array with some values. How can I search that array using jQuery for a value which is matched or close to it?
var a = ["foo","fool","cool","god","acl"];
If I want to search for c, then it should return cool but not acl.
How I can achieve that?
Try this:-
arr = jQuery.grep(a, function (value) {
search = /c/gi;
if(value.match(search)) return true;
return false;
});
or
function find(arr) {
var result = [];
for (var i in arr) {
if (arr[i].match(/c/)) {
result.push(arr[i]);
}
}
return result;
}
window.onload = function() {
console.log(find(["foo","fool","cool","god","acl"]));
};
Use substring to check if each string in the array begins with the string you are searching for:
var strings = [ "foo", "cool", "acl" ];
var needle = "c";
for (var i = 0; i < strings.length; ++i) {
if (strings[i].substring(0, needle.length) === needle) {
alert("found: " + strings[i]);
}
}
A simple way to do it is to check for words starting with 'c' and iterate of the array.
var ar = ['acl','cool','cat']
for(var i = 0 ; i<ar.length ; i++){
console.log(ar[i].match(/^c/))
}
//Prints:
//null
//["c", index: 0, input: "cool"]
//["c", index: 0, input: "cat"]
You can use the filter method which is available since JavaScript 1.6. It will give you back an array with the filtered values. Very handy if you want to match multiple items.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var a = ["foo","fool","cool","god","acl"];
var startsWith = 'c';
a.filter(function (value) {
return value && value.length > 0 && value[0] == startsWith;
});
// yields: ["cool"]
var a = ["foo","fool","cool","god","acl"];
var Character="f";
for(i=0;i<a.length;i++){
if(a[i].indexOf(Character)!=-1){
document.write(a[i]+"<br/>");
}
}
I have two arrays
var array1 = ['me','you','our'];
var array2 = ['us','they','all'];
I have another array
var arrayList = [array1, array2]
Now I have one value which I want to compare with each value of each array inside arrayList.
How can we do that?
Try this...
var yourValue;
for(var i=0;i<arrayList.length;i++)
{
for(var j=0;j<arrayList[i].length;j++)
{
if(arrayList[i][j] == yourValue)
{
//
//
}
}
}
var val='your value';
for(var i=0;i<arrayList.length;i++)
{
if(arrayList[i].indexOf(val)>-1){
// do something
// and break
}
}
Loop through arrayList then use indexOf.
var val = 'you';
for(var i = 0; i < arrayList.length; i++){
if(arrayList[i].indexOf(val) !== -1){
alert('match');
}
}