Javascript - Remove duplicates value in array - javascript

But I want to leave last two duplicated value in array just like
arr = [1,2,3,4,4,4,4,4,5,6,6,6]
and the result will be
result = [1,2,3,4,4,5,6,6]
The reason why I want to leave last two is I have 2 arrays like date and data and it must match with each other.
Thank you.

Using jquery you can use:
var newarr=[];
$.each(arr, function(i, e) {
if ($.inArray(e, newarr) == -1) newarr.push(e);
});
console.log(newarr)

Try this:
var arr = [1,2,3,4,4,4,4,4,5,6,6,6],
result = [],
fisrtOccurence = -1;
for(var i=0; i<arr.length; i++) {
fisrtOccurence = result.indexOf(arr[i]);
if(fisrtOccurence === -1) {
result.push(arr[i]);
} else {
if(result.indexOf(arr[i],fisrtOccurence+1) === -1) {
result.push(arr[i]);
}
}
}
console.log(result);

Try this solution : JSFiddle
var arr = [1,2,3,4,4,4,4,4,5,6,6,6]
// using reduce function of array
Array.prototype.unique = function() {
return this.reduce(function(previousValue, current) {
if (previousValue.indexOf(current) < 0) {
previousValue.push(current);
}
return previousValue;
}, []);
}
console.log(arr.unique());
// using filter
var filteredArray= arr.filter(function(element, index, self) {
return index == self.indexOf(element);
});
console.log(filteredArray);

Demo
Try this
newarr = [];
testarr = [];
duplicatearr = [];
locArray = [1,2,3,4,4,4,4,4,5,6,6,6];
for (var i = 0; i<locArray.length;i++)
{
var idx = $.inArray(locArray[i], testarr);
if (idx == -1) {
testarr.push(locArray[i]);
newarr.push(locArray[i]);
}
else
{
var id = $.inArray(locArray[i], duplicatearr);
if (id == -1) {
newarr.push(locArray[i]);
duplicatearr.push(locArray[i]);
}
}
}
console.log(newarr);

Related

how to reindex object start from 0

I have an object output from below code how to set the index start from 0 in js?
Object
3: Object
id: 34
type: 0
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[i] = {};
obj[i]['id'] = data_id;
obj[i]['type'] = data_type;
}
}
console.log(obj);
Needs more jQuery ?
var arr = $(".list").filter(function() {
return $(this).data('type') != 0;
}).map(function() {
return { id : $(this).data('id'), type : $(this).data('type') };
}).get();
FIDDLE
Actually if you want to start in 0, use another variable and not "i" (which I think is 3 when you use it as index).
var obj = {};
var edited = false;
var obj_idx = 0;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[obj_idx] = {};
obj[obj_idx]['id'] = data_id;
obj[obj_idx]['type'] = data_type;
obj_idx += 1;
}
}
console.log(obj);
I think this time obj will be something like:
Object
0: Object
id: 34
type: 0
you could fake object as array by Array.prototype.push.call, in that way you could also gain the side effect: obj.length. it's kinda ninja and elegant :]
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
Array.prototype.push.call(obj, {id: data_id, type: data_type});
}
}
I am going to give a very simple and readable example. Say you've got an object with the following structure:
Object
0: Object
key: 'some-key'
value: 'some-value'
1: Object
...
Then you might want to delete an entry from it and reindex the whole thing, this is how I do it:
// obj is Object from above
const reIndexed = Object.entries(obj).map((element, index) => {
if (parseInt(element[0] != index) {
element[0] = index.toString();
}
return element;
});

How to filter elements in array in JavaScript object

If I have a JavaScript object like this:
{"products":
[
{
"id":"6066157707315577",
"reference_prefix":"BB",
"name":"BeanieBaby",
"product_line":false,
"has_ideas":true
},
{
"id":"6066197229601550",
"reference_prefix":"BBAGS",
"name":"BlackBags",
"product_line":false,
"has_ideas":false
}
],
"pagination": {
"total_records":4,
"total_pages":1,
"current_page":1
}
}
How do I write a function in js to loop over each pair and only return the elements of the array where has_ideas === true?
I have started with this but I'm stuck. Clearly I am new to this. Any help appreciated.
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
var obj = json[i];
if (json[i].id === "has_ideas" && json[i].value === true) {
return json;
}
return [];
}
}
You can filter out each pair by simply checking that property:
var json = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}
var stuff = json.products.filter(function(obj) {
return obj.has_ideas === true
});
console.log(stuff);
Demo:http://jsfiddle.net/bsyk18cb/
try this
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
if(json[i].has_ideas === true){
return json;
}
return [];
}
}
You want to check the "has_ideas" attribute and if true, return the id.
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
if (json[i].has_ideas === true) {
return json[i].id;
}
return [];
}
}
Use code below.
this will return array of elements having has_ideas=true
var json = "{'products':"+
"["+
"{"+
"'id':'6066157707315577',"+
"'reference_prefix':'BB',"+
"'name':'BeanieBaby',"+
"'product_line':false,"+
"'has_ideas':true"+
"},"+
"{"+
"'id':'6066197229601550',"+
"'reference_prefix':'BBAGS',"+
"'name':'BlackBags',"+
"'product_line':false,"+
"'has_ideas':false"+
"}"+
"],"+
"'pagination': {"+
"'total_records':4,"+
"'total_pages':1,"+
"'current_page':1"+
"}"+
"}";
function filter(){
var jsonArr = [];
var gList = eval( "(" + json + ")");
alert(gList.products.length);
for(var i=0;i<gList.products.length;i++){
if(gList.products[i].has_ideas){
jsonArr.push(gList.products[i]);
}
}
return jsonArr;
}
Demo

Remove object from array object Jquery

I am creating array object like follows:
var numberOfSameDeficiency = [];
for (var i = 0; i < result.length; i++) {
var deficiencyId = result[i].Deficiency_Id;
var deficiencyName = result[i].DeficiencyName;
//check to see if this deficiency is already in the list of available selections
if ($("#drpDeficiency option[value='" + deficiencyId + "']").length == 0) {
var option = $('<option>');
option.attr('value', deficiencyId);
option.text(deficiencyName);
$select.append(option);
}
else {
Tests = {};
Tests.TestId = testId;
Tests.DeficiencyId = deficiencyId;
numberOfSameDeficiency.push(Tests);
}
}
And I want to remove object on different function like this:
for (var i = 0; i < result.length; i++) {
console.log(numberOfSameDeficiency);
var isFound = false;
var deficiencyId = result[i].Deficiency_Id;
if (numberOfSameDeficiency) {
numberOfSameDeficiency.forEach(function (entry) {
if (entry.DeficiencyId != deficiencyId) {
isFound = true;
**numberOfSameDeficiency.splice(entry, 1); // Generating Error (Remove all items from array object)**
return;
}
});
// console.log("end if");
}
if (!isFound) {
$("#drpDeficiency option[value='" + deficiencyId + "']").remove();
}
}
So what line code should be there to remove particular object from array object.
Try this
for( i=myArray.length-1; i>=0; i--) {
if( myArray[i].field == "money") myArray.splice(i,1);
}
This also works
myArray = [{name:"Alpesh", lines:"2,5,10"},
{name:"Krunal", lines:"1,19,26,96"},
{name:"Deep",lines:"3,9,62,36" }]
johnRemovedArray = myArray
.filter(function (el) {
return el.name !== "Krunal";
});
Create this prototype function:
Array.prototype.removeElement = function (el) {
for(let i in this){
if(this.hasOwnProperty(i))
if(this[i] === el)
this.splice(i, 1);
}
}
Then call:
let myArray = ['a','b','c','d'];
myArray.removeElement("c");
It also works with objects:
let myObj1 = {name: "Mike"},
myObj2 = {name: "Jenny"},
myArray = [myObj1, myObj2];
myArray.removeElement(myObj2);

filter objects matching details

Functions works fine, they filter inventory by barcode, and manufacturer. I want to make it like default angularjs filtering. If I choose manufacturer - LG and barcode - 112 and if they don't match, then it shouldn't display anything.
But for now it displays separately, when i click on filter function it filters barcode when on filter2 function filter manufacturer
$scope.filter = function(barcode) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].barcode == barcode){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
$scope.filter2 = function(manufacturer) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].manufacturer == manufacturer){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
Try this
$scope.filter = function (barcode, manufacturer) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].barcode == barcode || $scope.inventories[i].manufacturer == manufacturer){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
You could create a more general way of filtering:
$scope.filterByBarcode = function(list, key, value) {
return list.filter(function(item){
return item[key] === value;
});
};
And when you filter you could call:
$scope.filtered_inventories = $scope.filter($scope.filter($scope.inventories, 'barcode', 112), 'manufacturer', 'LG')
But to simplify that you could create a function:
$scope.filterByBarcodeAndManufacturer = function(barcode, manufacturer) {
$scope.filtered_inventories =
$scope.filter($scope.filter($scope.inventories, 'barcode', barcode), 'manufacturer', manufacturer);
}

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

Categories

Resources