0

I have JSON Data and i need last obj value from same type obj values.

I want to Get last index of Foo value Bar.

I know how to get last index of json array.

var data = [{
    "foo": "bar"
  },
  {
    "foo": "bar-1"
  },
  {
    "foo": "bar-2"
  },
  {
    "foo": "bar-1"
  },
  {
    "foo": "bar"
  },
  {
    "foo": "bar-1"
  },

]



$.each(data, function(key, val) {
  if (val.foo == "bar") {
    console.log(key);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

3 Answers3

2

No need for jQuery, just loop in reverse:

Assuming the element you want IS near the end. If not, then any of the reduce or map answers given will likely not be much slower

var data = [
  {"foo": "bar"},
  {"foo": "bar-1"},
  {"foo": "bar-2"},
  {"foo": "bar-1"},
  {"foo": "bar"},
  {"foo": "bar-1"} // no comma on the last
]


// Find the last `bar`

for (var i=data.length-1;i>=0;i--) {
  if (data[i].foo == "bar") {
    console.log('Last of Foo Bar is ' +i);
    break;
  }
}

// Find the last `bar` AND the last bar-1
var bars = { "bar":-1, "bar-1":-1, "done":0 }, numBars = 2;
for (var i=data.length-1;bars["done"]<numBars && i>=0;i--) {
  if (bars[data[i].foo]==-1) {
    bars[data[i].foo] = i;
    bars["done"]++;
  }
}
console.log(JSON.stringify(bars));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

You could just use reduce() and when element is found set accumulator value to index of that element. So then index of last element found will be returned.

var data = [{"foo":"bar"},{"foo":"bar-1"},{"foo":"bar-2"},{"foo":"bar-1"},{"foo":"bar"},{"foo":"bar-1"}]

var lastIndex = data.reduce(function(r, e, i) {
  if(e.foo == 'bar') r = i
  return r;
}, null)

console.log(lastIndex)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

Actually you don't need to use jQuery to solve it.

var data = [{foo:"bar"},{foo:"bar-1"},{foo:"bar-2"},{foo:"bar-1"},{foo:"bar"},{foo:"bar-1"}],
    indexes = [];
    data.forEach((v,i) => v.foo == 'bar' ? indexes.push(i) : v);

console.log(`Index of last 'bar' key is ${indexes[indexes.length-1]}`);
kind user
  • 40,029
  • 7
  • 67
  • 77
  • Again that will take much longer than just reverse looping – mplungjan Mar 03 '17 at 14:58
  • @mplungjan *Much longer*. Oh, please. – kind user Mar 03 '17 at 15:07
  • Of course with the array in OP's example it does not matter, However we have no way of knowing how big the actual array is. Never assume that the example matches reality. You could be creating thousands of items just to find the last of the ones your pushed. – mplungjan Mar 03 '17 at 15:10
  • @mplungjan I just mean that it would be perceptible only for very huge arrays. In this particular case, it doesn't really matter. But I also agree with you, we can't just assume that OP won't use it for bigger variables. (: – kind user Mar 03 '17 at 15:12