Piyush Piyush - 5 months ago 8
JSON Question

Search in json array

I am new to json. My json array

[{"seat_number":"834"},{"seat_number":"8F3"},{"seat_number":"891"},
{"seat_number":"814"},{"seat_number":"4081"},{"seat_number":"8F1"},
{"seat_number":"8F9"},{"seat_number":"4039"},{"seat_number":"0"},
{"seat_number":"509"},{"seat_number":"662"},{"seat_number":"561"},
{"seat_number":"791"},{"seat_number":"849"}]


I want to find seat number already exist in array.

if(($scope.employeeSeat.seat_array.indexOf($scope.employeeData.new_seat_number))>-1)
{
alert('Seat number is already assigned.Please Check');
}


What is wrong?

Answer

You can do it the hard way if you want

var data = [
  {"seat_number":"834"},{"seat_number":"8F3"},
  {"seat_number":"891"},{"seat_number":"814"},
  {"seat_number":"4081"},{"seat_number":"8F1"},
  {"seat_number":"8F9"},{"seat_number":"4039"},
  {"seat_number":"0"},{"seat_number":"509"},
  {"seat_number":"662"},{"seat_number":"561"},
  {"seat_number":"791"},{"seat_number":"849"}
];

function matchingSeat(x) {
  return data.some(function(elem) {
    return elem.seat_number === x;
  });
}

console.log("831", matchingSeat("834")); // 834 true
console.log("8F3", matchingSeat("8F3")); // 8F3 true
console.log("999", matchingSeat("999")); // 999 false

I think that's a total pain tho. Once you have some reusable utility functions at your disposal, this problem becomes a lot easier to solve.

Don't freak out: the ES5 solution is below

// ES6
// reusable lib
let prop = y => x => x[y];

let comp = f => g => x => f(g(x));

let eq = y => x => x === y;

let some = f => xs => xs.some(f);

Now write some helpers to solve your task

let eqSeat = x => comp(eq(x))(prop("seat_number"));
let hasSeat = comp(some)(eqSeat);

Check it out

console.log("831", hasSeat("834")(data)); // 831 true
console.log("8F3", hasSeat("8F3")(data)); // 8F3 true
console.log("999", hasSeat("999")(data)); // 999 false

Here's the same code in ES5

// ES5
// reusable lib
var prop = function prop(y) {
  return function (x) {
    return x[y];
  };
};

var comp = function comp(f) {
  return function (g) {
    return function (x) {
      return f(g(x));
    };
  };
};

var eq = function eq(y) {
  return function (x) {
    return x === y;
  };
};

var some = function some(f) {
  return function (xs) {
    return xs.some(f);
  };
};

Your helpers

var eqSeat = function eqSeat(x) {
  return comp(eq(x))(prop("seat_number"));
};

var hasSeat = comp(some)(eqSeat);

Try it out

console.log("831", hasSeat("834")(data)); // 831 true
console.log("8F3", hasSeat("8F3")(data)); // 8F3 true
console.log("999", hasSeat("999")(data)); // 999 false
Comments